我有以下使用熊猫构建堆积条形图的代码:
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, ax = plt.subplots(figsize = (9,4.2), dpi = 120)
ax.bar(dfBar2['X'], dfBar2['value'], edgecolor = 'black',color = colors)
...
有没有一种简便的方法可以通过我的方法制作堆积的条形图?我发现的示例最终使用了enumerate
或for
循环,这些循环看起来太复杂了,并且肯定不是在matplotlib中制作简单堆积条形图的最佳方法(尤其是Pandas在一行中做到这一点) )?
答案 0 :(得分:0)
好吧,我发现了一种解决方法,将ax=ax
放入大熊猫图中,似乎比使用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
等,但至少对我有用。