【问题标题】:Pandas df.plot set color proportional to a dataframe columnPandas df.plot 设置颜色与数据框列成比例
【发布时间】:2020-02-26 17:52:21
【问题描述】:

问题:

我有一个 pandas 数据框 df,其中 6 行代表不同的变量。
我想在条形图中绘制前两列,我想使用第三列 score 根据现有颜色图对条形进行着色,例如 matplotlib viridis 。

这个数据框看起来像这样:

    ID  count   score
0    4      1       3
1    5      4       4
2    5      8       5
3    3      7       2
4    1      5       5
5    1      3       4

我的代码目前的样子:

df.plot('ID', 'count', kind='bar', figsize=(15,5), ax=plt.subplot(122), colors=cm.viridis.colors)
plt.show()

但所有条的颜色都是独特的紫色。
比如说,我想根据我的score 列中的值按比例对 viridis 颜色图进行采样。
有没有一种简单的方法可以实现这一目标?

编辑[2019-10-31]:

使用第一个答案中提出的seaborn 会给我一个错误:

my_palette = sns.color_palette(plt.get_cmap('viridis'), 5)
sns.barplot(x="New ID", y="count", hue="Note", data=df, palette=my_palette)

返回的错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-48-1943cafa0d79> in <module>
----> 1 my_palette = sns.color_palette(plt.get_cmap('viridis'), 5)

/usr/local/lib/python3.6/dist-packages/seaborn/palettes.py in color_palette(palette, n_colors, desat)
    238 
    239     # Always return as many colors as we asked for
--> 240     pal_cycle = cycle(palette)
    241     palette = [next(pal_cycle) for _ in range(n_colors)]
    242 

TypeError: 'ListedColormap' object is not iterable

编辑[2019-11-05]:

使用建议的代码会导致生成的图表中的条形与 x 刻度未对齐(我希望它位于 x 轴条形下方的中心),尤其是当每个类别只有一个条形时,下一个图显示:

此外,我希望能够考虑 'NaN' 列中的 'NaN' 值。 目前,如果有一个 'NaN' 值,它会提高一个:
TypeError: unsupported operand type(s) for /: 'str' and 'int'
所以,我必须将此值设置为 0,即使它不是真正的零。

【问题讨论】:

  • 如果'score'中有一个NaN,你想要什么颜色?
  • 但是如果我的count 属性中有'NaN',实际上没有bar。所以,颜色并不重要。

标签: python pandas matplotlib colormap


【解决方案1】:

最简单的就是这样使用seaborn.barplot

import seaborn as sns
ax = sns.barplot(x="ID", y="count", hue="score", data=df, palette=your_palette)

您可以这样创建调色板:

your_palette = sns.color_palette('inferno', n_point)

其中n_point 是您的自定义调色板中不同颜色的数量。

希望对你有帮助。

【讨论】:

  • 感谢您的回答,不幸的是,这给了我一个错误。我的seaborn 版本是0.9.0(使用pip 从PyPi 下载)。
  • 我更改了代码。很抱歉这个错误。 color_palette 是一种接受颜色图名称和点数的方法。我再次测试它,它现在可以工作了。
  • 我可以看到条形图与 x-ticks 随机对齐,这很烦人,我搜索了文档但没有找到任何修复它。
  • 我不认为它们是“随机”对齐的。您提供的示例数据有两个 id=1 的条目。您希望如何绘制这些图?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 2018-02-12
  • 2013-02-16
  • 1970-01-01
  • 2017-11-14
  • 1970-01-01
相关资源
最近更新 更多