【问题标题】:Is there a simple way to build a stacked bar chart in matplotlib?有没有一种简单的方法可以在 matplotlib 中构建堆积条形图?
【发布时间】:2019-05-15 19:32:54
【问题描述】:

我有以下代码使用 pandas 构建堆叠条形图:

dfTech = pd.DataFrame({'year':[2010,2011,2012,2013,2014,2015,2016,2017,2018],
                       'Other': [48.2,44.8,151.2,54.3,185,253.7,418.6,650,915], 
                       'Graphcore':[0,0,0,0,0,0,30,80,200], 
                       'Medopad Ltd':[0,0,0,0,0,0,0,0,120],
                       'BenevolentAI Limited': [0,0,0,0,0,0,0,0,115], 
                       'Blippar.Com': [0,0,0,0,0,45,54,0,63], 
                       'Draktrace': [0,0,0,0,0,40.5,65,75,50], 
                       'The Hut Group Limited': [0,0,0,0,0,0,0,168.9,0]})



dfTech.loc[:,['Other',  'Graphcore',    'Medopad Ltd',  'BenevolentAI Limited', 
              'Blippar.Com',    'Darktrace',    
              'The Hut Group Limited']].plot.bar(stacked=True,  figsize=(10,7))

这正是我想要的:

但是,我试图始终坚持使用我的代码的相同格式,即始终使用 matplotlib,并始终将 fig 和 axe 分开,即:

    fig, ax = plt.subplots(figsize = (9,4.2), dpi = 120)
    ax.bar(dfBar2['X'], dfBar2['value'], edgecolor = 'black',color = colors)
    ...

有没有一种简单的方法可以通过我的方法制作堆积条形图?我发现的示例最终使用了enumeratefor 循环,这看起来太复杂了,肯定不是在matplotlib 中制作简单堆叠条形图的最佳方式(尤其是Pandas 将它放在一行中)?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    好的,我通过将ax=ax 放入我的 pandas 图中找到了使用 pandas 的解决方法,这似乎比我发现在 matplotlib 中构建堆叠条形图的其他示例要好得多:

    fig, ax = plt.subplots(figsize = (7,5), dpi = 120)
    
    dfTech.loc[:,['Other',  'Graphcore',    'Medopad Ltd',  'BenevolentAI Limited', 
                  'Blippar.Com',    'Darktrace',    
                  'The Hut Group Limited']].plot.bar(stacked=True, ax=ax, figsize=(10,7))
    
    ax.set_xticklabels(['2010','2011','2012','2013','2014','2015','2016','2017', 
                        '2018'], weight = 'bold',fontsize = 9)
    ax.set_yticklabels(['0','200','400','600','800','1000', '1200', '1400'], 
                       weight = 'bold',fontsize = 9)
    
    ax.set_ylabel('Private Investments ($m)', fontsize = 11, labelpad = 20, 
                  fontdict=dict(weight='bold')) 
    
    
    
    etc.........
    

    仍然不确定是否有办法通过 matplotlib 轻松做到这一点,而不必使用 Pandas plot.bar 等,但至少它对我有用。

    【讨论】:

      猜你喜欢
      • 2010-09-24
      • 2011-02-16
      • 2020-08-27
      • 2018-01-17
      • 2019-11-28
      • 2018-11-30
      • 2021-02-27
      • 2010-09-06
      • 1970-01-01
      相关资源
      最近更新 更多