如何根据调色板

时间:2017-12-19 10:38:05

标签: python pandas matplotlib seaborn

我使用以下代码生成seaborn散点图:

import pandas as pd
from  matplotlib import pyplot
import seaborn as sns
%matplotlib inline

df = pd.DataFrame({
    'Year': [2010, 2011, 2010, 2011, 2012],
    'Event': ['A', 'A', 'B', 'B', 'B']
})

fig, ax = pyplot.subplots()
sns.stripplot(x="Year", y="Event", ax=ax, data=df,
              palette=sns.color_palette("deep", 50));

生成的图像是:

scatterplot

然而,当可能的标签数量增加时(例如:'事件' = [' A',' B',...' Z'],很难读取每个圆圈对应的y标签。

如何在调色板中编写涂有相应颜色的每个y标签(例如:Event)?

通常,在这个例子中,我希望A y标签用蓝色写,B用绿色写

2 个答案:

答案 0 :(得分:1)

  1. 为每个标签创建一个包含颜色的字典:

    dict_colors = {"A":"blue", "B":"green"}
    
  2. 将其映射到yticklabels:

    [label.set_color( dict_colors[label.get_text()] ) for label in ax.get_yticklabels()]
    

答案 1 :(得分:0)

对于记录,感谢jrjc的答案

,这是新代码
import pandas
from  matplotlib import pyplot
import seaborn as sns
%matplotlib inline

df = pandas.DataFrame({
    'Year': [2010, 2011, 2010, 2011, 2012],
    'Event': ['A', 'A', 'B', 'B', 'B']
})

fig, ax = pyplot.subplots()
pal = sns.color_palette("deep", 50)
sns.stripplot(x="Year", y="Event", ax=ax, data=df, palette=pal);
[label.set_color(pal[i]) for i, label in enumerate(ax.get_yticklabels())]

新生成的图像是:

enter image description here