【问题标题】:How can I set the colors per value when coloring plots by a DataFrame column?当按 DataFrame 列着色图时,如何设置每个值的颜色?
【发布时间】:2016-08-17 14:58:53
【问题描述】:

在 matplotlib(尤其是 pandas)中,如何将特定颜色映射到用于区分颜色的列的值?

假设我有一个专栏......

>> df["country"]
DE
EN
US
DE

...现在我想绘制 DataFrame 中的值,其中每个国家的颜色都不同。如何确定哪个国家/地区获得哪种颜色?用颜色图?很遗憾,我找不到合适的文档。

我想应用这样的字典:

# pseudo-code
colormapping = {"DE": "blue", ...}
df.plot(colorby="country", colormapping)

编辑:

这是一个示例 DataFrame。

    outlook   play  temperature country
0     sunny   True           25      DE
1     sunny   True           25      EN
2  overcast   True           19      DE
3      rain  False           21      US
4  overcast  False           33      IT
5      rain  False           27      EN
6      rain  False           22      FR
7  overcast   True           26      FR
8     sunny   True           13      FR
9     sunny   True           16      CH

【问题讨论】:

  • 你能提供一个样本dataframe吗?
  • @NickilMaveli:当然,请看我的编辑!
  • 你期待什么样的情节?

标签: python pandas matplotlib colors seaborn


【解决方案1】:

您可以通过使用seaborncategorical plotpalette 参数中指定色调级别的字典映射到对应的matplotlib 颜色来做到这一点,如下所示:

sns.set(style="whitegrid")
sns.swarmplot(x="outlook", y="temperature", hue="country", data=df, size=8,
              palette={'DE':'b', 'EN':'g', 'US':'r','IT':'c', 'FR':'y', 'CH':'k'})

【讨论】:

  • 这正是我想要的!谢谢:-)
  • 有点不幸的是,seaborn 处理这个比 matplotlib 本身更复杂,您可以在 c= 中直接传递带有颜色代码的列/数组作为参数...
猜你喜欢
  • 2014-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-21
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
相关资源
最近更新 更多