【问题标题】:Bar Chart Color Key is Incorrect条形图颜色键不正确
【发布时间】:2020-12-02 14:35:17
【问题描述】:

在 jupyter notebook 中使用 pandas,我正在为按动作分类着色的示例动作生成交互分数的条形图。分类为 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)

但我得到了这张图表:

你们看到应该是 黑色 的 CTRL 不是吗?与 Fist Swipe 相同,它 应该是黑色的。有谁知道我可以做些什么来纠正这个问题?

【问题讨论】:

  • 好吧,你对绘图调用的数据进行排序,但不是颜色,所以我猜你需要像 [colors[i] for i in cat_data.sort_values('Interaction_rounded')['Classification']] 这样的东西,或者在绘图之前更好地排序一次......
  • 哇,原来如此!我不知道我还必须对颜色的数据进行排序。非常感谢。

标签: python pandas matplotlib bar-chart data-visualization


【解决方案1】:

这是我的工作:

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

【讨论】:

  • 哇,这绝对是我下次要做的,以简化和简化流程。非常感谢保罗。
猜你喜欢
  • 2017-04-29
  • 1970-01-01
  • 2017-10-19
  • 1970-01-01
  • 1970-01-01
  • 2020-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多