gpt4 book ai didi

Python:按条件绘制多个正/负条形图

转载 作者:太空宇宙 更新时间:2023-11-03 15:37:47 26 4
gpt4 key购买 nike

这是我第一次用 python 绘制条形图。

我的 df 操作:

      key descript  score
0 noodles taste 5
1 noodles color -2
2 noodles health 3
3 apple color 7
4 apple hard 9

我的代码:

import matplotlib.pyplot as plt
op['positive'] = op['score'] > 0
op['score'].plot(kind='barh', color=op.positive.map({True: 'r', False: 'k'}), use_index=True)
plt.show()
plt.savefig('sample1.png')

输出:

Bar Chart

但这不是我所期望的。在这种情况下,我想通过不同的键绘制两个带有索引的图表,并且可能使用如下不同的颜色:

expected Bar Chart

我怎样才能做到这一点?

最佳答案

尝试:

fig, ax = plt.subplots(1,op.key.nunique(), figsize=(15,5), sharex=True)
i = 0

#Fix some data issues/typos
op['key']=op.key.str.replace('noodels','noodles')

for n, g in op.assign(positive=op['score'] >= 0).groupby('key'):
g.plot.barh(y='score', x='descript', ax=ax[i], color=g['positive'].map({True:'red',False:'blue'}), legend=False)\
.set_xlabel(n)
ax[i].set_ylabel('Score')
ax[i].spines['top'].set_visible(False)
ax[i].spines['right'].set_visible(False)
ax[i].spines['top'].set_visible(False)
ax[i].spines['left'].set_position('zero')
i += 1

输出:

enter image description here

更新为 yaxis 添加了标签移动 - 感谢这个 SO solution by @ ImportanceOfBeingErnest

fig, ax = plt.subplots(1,op.key.nunique(), figsize=(15,5), sharex=True)
i = 0

#Fix some data issues/typos
op['key']=op.key.str.replace('noodels','noodles')

for n, g in op.assign(positive=op['score'] >= 0).groupby('key'):
g.plot.barh(y='score', x='descript', ax=ax[i], color=g['positive'].map({True:'red',False:'blue'}), legend=False)\
.set_xlabel(n)
ax[i].set_ylabel('Score')
ax[i].spines['top'].set_visible(False)
ax[i].spines['right'].set_visible(False)
ax[i].spines['top'].set_visible(False)
ax[i].spines['left'].set_position('zero')
plt.setp(ax[i].get_yticklabels(), transform=ax[i].get_yaxis_transform())
i += 1

输出:

enter image description here

关于Python:按条件绘制多个正/负条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54000676/

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