gpt4 book ai didi

python - 在 matplotlib 中的嵌套字典的数据上创建图形(绘图)

转载 作者:行者123 更新时间:2023-12-01 22:14:42 24 4
gpt4 key购买 nike

我可以根据“简单”字典在 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())

enter image description here

但是,如何在一个我不知道的地 block 上根据这些词典的数据创建两个图形?

NG1={'need1': [{'good1': 3, 'good2': 4}], 'need2': [{'good2': 2, 'good3': 2}]}
NG2={'need1': [{'good1': 13, 'good2': 23}], 'need2': [{'good2': 8, 'good3': 14}]}

如下图所示

enter image description here

最佳答案

使用 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()

交付

bar plot

编辑更新

我无法以这种方式准确创建您需要的内容,您需要尝试使用不同的字形和图形,而我没有技能或时间来执行此操作,但我可以以正确的方式提供数据

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()

enter image description here

关于python - 在 matplotlib 中的嵌套字典的数据上创建图形(绘图),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46791559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com