Xavier M
Xavier M

Reputation: 549

How to set the color of y-label according to a palette

I use the following code to generate a seaborn scatterplot:

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

The resulting image is:

scatterplot

However, when the number of possible labels grows (eg:'Events'= ['A','B',...'Z'], it is difficult to read the y label corresponding to each circle.

How can I write each y-label (eg: Event) painted with its corresponding color in the palette ?

Typically, in this example, I would like the A y-label to be written in a blue color and B in green

Upvotes: 1

Views: 719

Answers (2)

Xavier M
Xavier M

Reputation: 549

For the records, here is the new code thanks to jrjc's answer

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

The new resulting image is:

enter image description here

Upvotes: 0

jrjc
jrjc

Reputation: 21873

  1. Create a dictionary with your colors for each label:

    dict_colors = {"A":"blue", "B":"green"}
    
  2. map it on the yticklabels:

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

Upvotes: 1

Related Questions