如何从三组具有不同数量和顺序的索引的字典中制作一个三列的条形图?
How to make a bar chart with three columns from three sets of dictionaries with a different number and order of indices?
我正在尝试根据我生成的一些 Counter 词典创建一个三列条形图,但无法正常工作。
我能够生成一个计数器字典的条形图,但不是所有三个在每个索引处都有一个列字典。
f_cond_count=dict(Counter(f_cond_plot))
f_pow_count=dict(Counter(f_pow_plot))
f_mom_count=dict(Counter(f_mom_plot))
print("cond",f_cond_count)
print("pow",f_pow_count)
print("mom",f_mom_count)
df = pd.DataFrame.from_dict((f_cond_count, f_pow_count, f_mom_count), 'index')
df.plot.bar()
plt.show()
这行代码将打印以下内容:
cond {0.1: 33, 0.2: 36, 0.300000000000000004: 36, 0.4: 36, 0.5: 39, 0.6: 39, 0.7000000000000001: 39, 0.8: 39, 0.9: 39}
pow {0.7000000000000001:54, 0.8:81, 0.9:201}
妈妈 {0.4:94, 0.5:27, 0.6:27, 0.7000000000000001:18, 0.8:9, 0.9:9, 0.30000000000000004:85, 0.2:67}
如果我使用以下方法,我可以使用一本字典:
df = pd.DataFrame.from_dict(f_cond_count, 'index')
df.plot.bar()
plt.show()
我得到一个条形图,x 轴为 [0.1、0.2、0.30000000004、0.4 等],y 轴为数字 [33、36、36、36 等]。
我收到错误消息:“'tuple' 对象没有属性 'values'”,当我尝试执行所有这三个操作时,我不确定为什么。我也不确定它是否会起作用,因为字典大小不同,有些没有某些索引的条目。我正在尝试创建类似于此线程
中发布的解决方案的内容
您可以先使用 Series
从三个词典中创建一个 DataFrame,然后一次绘制所有三个条形图。如您所见,x-ticklabels 上的值存在浮点问题。
添加最后两行,否则 tick-labels 会显示精度问题
df = pd.DataFrame({'cond': pd.Series(f_cond_count), 'powc': pd.Series(f_pow_count),
'mom': pd.Series(f_mom_count) })
ax = df.plot.bar()
labs = [round(float(t.get_text()), 1) for t in ax.axes.get_xmajorticklabels()]
ax.set_xticklabels(labs);
我正在尝试根据我生成的一些 Counter 词典创建一个三列条形图,但无法正常工作。
我能够生成一个计数器字典的条形图,但不是所有三个在每个索引处都有一个列字典。
f_cond_count=dict(Counter(f_cond_plot))
f_pow_count=dict(Counter(f_pow_plot))
f_mom_count=dict(Counter(f_mom_plot))
print("cond",f_cond_count)
print("pow",f_pow_count)
print("mom",f_mom_count)
df = pd.DataFrame.from_dict((f_cond_count, f_pow_count, f_mom_count), 'index')
df.plot.bar()
plt.show()
这行代码将打印以下内容:
cond {0.1: 33, 0.2: 36, 0.300000000000000004: 36, 0.4: 36, 0.5: 39, 0.6: 39, 0.7000000000000001: 39, 0.8: 39, 0.9: 39}
pow {0.7000000000000001:54, 0.8:81, 0.9:201}
妈妈 {0.4:94, 0.5:27, 0.6:27, 0.7000000000000001:18, 0.8:9, 0.9:9, 0.30000000000000004:85, 0.2:67}
如果我使用以下方法,我可以使用一本字典:
df = pd.DataFrame.from_dict(f_cond_count, 'index')
df.plot.bar()
plt.show()
我得到一个条形图,x 轴为 [0.1、0.2、0.30000000004、0.4 等],y 轴为数字 [33、36、36、36 等]。
我收到错误消息:“'tuple' 对象没有属性 'values'”,当我尝试执行所有这三个操作时,我不确定为什么。我也不确定它是否会起作用,因为字典大小不同,有些没有某些索引的条目。我正在尝试创建类似于此线程
您可以先使用 Series
从三个词典中创建一个 DataFrame,然后一次绘制所有三个条形图。如您所见,x-ticklabels 上的值存在浮点问题。
添加最后两行,否则 tick-labels 会显示精度问题
df = pd.DataFrame({'cond': pd.Series(f_cond_count), 'powc': pd.Series(f_pow_count),
'mom': pd.Series(f_mom_count) })
ax = df.plot.bar()
labs = [round(float(t.get_text()), 1) for t in ax.axes.get_xmajorticklabels()]
ax.set_xticklabels(labs);