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

时间:2019-01-02 02:47:37

标签: python matplotlib bar-chart

这是我第一次用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

我该怎么做?

1 个答案:

答案 0 :(得分:2)

尝试:

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