2

I'm making a simple pairplot with Seaborn in Python that shows different levels of a categorical variable by the color of plot elements across variables in a Pandas DataFrame. Although the plot comes out exactly as I want it, the categorical variable is binary, which makes the legend quite meaningless to an audience not familiar with the data (categories are naturally labeled as 0 & 1).

An example of my code:

g = sns.pairplot(df, hue='categorical_var', palette='Set3')

Is there a way to change legend label text with pairplot? Or should I use PairGrid, and if so how would I approach this?

Paul H
  • 65,268
  • 20
  • 159
  • 136
RF_PY
  • 343
  • 1
  • 3
  • 9

2 Answers2

1

Found it! It was answered here: Edit seaborn legend

g = sns.pairplot(df, hue='categorical_var', palette='Set3')
g._legend.set_title(new_title)

Raquel
  • 371
  • 3
  • 5
0

Since you don't provide a full example of code, nor mock data, I will use my own codes to answer.

First solution

The easiest must be to keep your binary labels for analysis and to create a column with proper names for plotting. Here is a sample code of mine, you should grab the idea:

def transconum(morph):
    if (morph == 'S'):
        return 1.0
    else:
        return 0.0

CompactGroups['MorphNum'] = CompactGroups['MorphGal'].apply(transconum)

Second solution

Another way would be to overwrite labels on the flight. Here is a sample code of mine which works perfectly:

grid = sns.jointplot(x="MorphNum", y="PropS", data=CompactGroups, kind="reg")
grid.set_axis_labels("Central type", "Spiral proportion among satellites")
grid.ax_joint.set_xticks([0, 1, 1])
plt.xticks(range(2), ('$Red$', '$S$')) 
Matt
  • 763
  • 1
  • 7
  • 25
  • 1
    just a comment to your first solution: can be reduced into a list comprehension `CompactGroups['MorphNum'] = [1 if i == True else 0 for i in CompactGroups['MorphGal'] == 'S']` – grg rsr Jul 16 '17 at 09:39