条形图颜色键不正确

问题描述

在jupyter笔记本中使用熊猫,我正在为该Motion的分类所着色的示例Motion生成一个交互作用得分的条形图。分类为VS,SUB,OBV,VO和CTRL。因此,我将此代码用于绘图:

colors = {'VS':'blue','SUB':'green','OBV': 'orange','VO': 'red','CTRL': 'black'}


cat_data.sort_values('Interaction_rounded').plot.bar(x='Motion',y='Interaction_rounded',rot=90,title='All Motions Interaction score Colored by Classification',color = [colors[i] for i in cat_data['Classification']],fontsize = 8,legend = False)

但是我得到这张图:

enter image description here

你们看到应该是黑色的CTRL不是吗?与“拳头轻扫”相同,不是应该是黑色的。有人知道我可以做些什么来纠正这个问题吗?

解决方法

这就是我要做的:

  1. 将颜色预先计算为数据框中的一列,
  2. 对整个数据框进行排序,然后
  3. 将数据帧的副本通过管道传递到可以访问新排序的数据的绘图功能:
colors = {'VS':'blue','SUB':'green','OBV': 'orange','VO': 'red','CTRL': 'black'}


_ = (
    cat_data
        .sort_values('Interaction_rounded')
        .assign(colors=lambda df: df['Classification'].map(colors)
        .pipe(lambda df: 
            df.plot.bar(
                x='Motion',y='Interaction_rounded',rot=90,title='All Motions Interaction Score Colored by Classification',color=df['colors'],# now you can access the latest version of the dataframe
                fontsize=8,legend=False
            )
        )
)