【问题标题】:How to create a grouped bar plot from lists如何从列表创建分组条形图
【发布时间】:2021-10-14 23:57:20
【问题描述】:
  • 我正在尝试绘制条形图,用于比较 2 种不同情况下的多个项目的数量。
  • 所需的输出将是一个 4+4 = 8 个条形图,彼此相邻,表示每种情况下每种类型的数量。
  • 这是我编写的初始代码,它没有达到我的预期。我该如何修改?
import numpy
import matplotlib.pyplot as plt

names = ["a","b","c","d"]
case1 = [5,7,5,6]
case2 = [7,4,8,5]

plt.hist(case1)
plt.show()

【问题讨论】:

    标签: python pandas matplotlib plot bar-chart


    【解决方案1】:
    import pandas as pd
    import matplotlib.pyplot as plt
    
    names = ["a","b","c","d"]
    case1 = [5,7,5,6]
    case2 = [7,4,8,5]
    
    # create the dataframe
    df = pd.DataFrame({'c1': case1, 'c2': case2}, index=names)
    
    # display(df)
       c1  c2
    a   5   7
    b   7   4
    c   5   8
    d   6   5
    
    # plot
    ax = df.plot(kind='bar', figsize=(6, 4), rot=0, title='Case Comparison', ylabel='Values')
    plt.show()
    

    • 尝试以下python 2.7
    fig, ax = plt.subplots(figsize=(6, 4))
    df.plot.bar(ax=ax, rot=0)
    ax.set(ylabel='Values')
    plt.show()
    

    【讨论】:

      【解决方案2】:

      可以通过调整 code 来解决您的问题。

      # importing pandas library
      import pandas as pd
      # import matplotlib library
      import matplotlib.pyplot as plt
        
      # creating dataframe
      df = pd.DataFrame({
          'Names': ["a","b","c","d"],
          'Case1': [5,7,5,6],
          'Case2': [7,4,8,5]
      })
        
      # plotting graph
      df.plot(x="Names", y=["Case1", "Case2"], kind="bar")
      

      【讨论】:

        【解决方案3】:

        仅限 Matplotlib(加上 numpy.arange)。

        如果您考虑一下,很容易正确放置条形组。

        import matplotlib.pyplot as plt
        from numpy import arange
        
        places = ["Nujiang Lisu","Chuxiong Yi","Liangshan Yi","Dehong Dai & Jingpo"]
        animals = ['Pandas', 'Snow Leopards']
        
        n_places = len(places)
        n_animals = len(animals)
        
        animals_in_place = [[5,7,5,6],[7,4,8,5]]
        
        ### prepare for grouping the bars    
        total_width = 0.5 # 0 ≤ total_width ≤ 1
        d = 0.1 # gap between bars, as a fraction of the bar width, 0 ≤ d ≤ ∞
        width = total_width/(n_animals+(n_animals-1)*d)
        offset = -total_width/2
        
        ### plot    
        x = arange(n_places)
        fig, ax = plt.subplots()
        for animal, data in zip(animals, animals_in_place):
            ax.bar(x+offset, data, width, align='edge', label=animal)
            offset += (1+d)*width
        ax.set_xticks(x) ; ax.set_xticklabels(places)
        fig.legend()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-05-27
          • 1970-01-01
          • 1970-01-01
          • 2019-11-11
          • 2018-12-22
          • 1970-01-01
          相关资源
          最近更新 更多