我可以根据'简单'字典在matplotlib中构建一个简单的图:
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), D.keys())
但是,如何在我不知道的情节上创建这些词典数据的两个图形呢?
NG1={'need1': [{'good1': 3, 'good2': 4}], 'need2': [{'good2': 2, 'good3': 2}]}
NG2={'need1': [{'good1': 13, 'good2': 23}], 'need2': [{'good2': 8, 'good3': 14}]}
如下图所示
答案 0 :(得分:3)
使用pandas
你可以做我认为你想要的事情
NG1={'need1': {'good1': 3, 'good2': 4}, 'need2': {'good2': 2, 'good3': 2}}
NG2={'need1': {'good1': 13, 'good2': 23}, 'need2': {'good2': 8, 'good3': 14}}
(注意缺少[]
)
combined_df = pd.concat({'ng1': pd.DataFrame(NG1), 'ng2': pd.DataFrame(NG2)}).unstack(0)
combined_df
need1 need2
ng1 ng2 ng1 ng2
good1 3.0 13.0 NaN NaN
good2 4.0 23.0 2.0 8.0
good3 NaN NaN 2.0 14.0
根据您想要的具体内容,您可以省略unstack
combined_df.plot.bar()
递送
我无法以这种方式准确创建你需要的东西,你需要使用不同的字形和数字,我没有技能或时间去做,但我可以正确的方式提供数据< / p>
combined_df = pd.concat({'ng1': pd.DataFrame(NG1), 'ng2': pd.DataFrame(NG2)}).stack()
combined_df.index.names = ['ng', 'good', 'need']
combined_df = combined_df.unstack(['good'])
combined_df['sum'] = combined_df.sum(axis=1)
combined_df
good good1 good2 good3 sum
ng need
ng1 need1 3.0 4.0 NaN 7.0
need2 NaN 2.0 2.0 4.0
ng2 need1 13.0 23.0 NaN 36.0
need2 NaN 8.0 14.0 22.0
combined_df.plot.bar()
答案 1 :(得分:3)
添加到@MaartenFabré 's solution,您可以将总和作为另一个条形图在后台绘制,将总和绘制为单独的条形图并使其无填充,
combined_df['sum'].plot.bar(zorder=0, fill=False)
完整的解决方案:
import matplotlib.pyplot as plt
import pandas as pd
NG1={'need1': {'good1': 3, 'good2': 4}, 'need2': {'good2': 2, 'good3': 2}}
NG2={'need1': {'good1': 13, 'good2': 23}, 'need2': {'good2': 8, 'good3': 14}}
combined_df = pd.concat({'ng1': pd.DataFrame(NG1), 'ng2': pd.DataFrame(NG2)}).stack()
combined_df.index.names = ['ng', 'good', 'need']
combined_df = combined_df.unstack(['good'])
combined_df.plot.bar()
combined_df['sum'] = combined_df.sum(axis=1)
combined_df['sum'].plot.bar(zorder=0, fill=False)
plt.show()