How to set titles to lmplots according to cateogorical variable?

Viewed 160

I need to plot a sns lmplot of two quantitative variables according to a qualitative variable (sex). When I add hue and col arguments as follows:

g = sns.lmplot(x = "exper", y = "wage", hue = "female",col = "female", data = df, sharey = False)

it all works out. Yet instead of titling each plot as female = 0 and female = 1, I want to title them as Men and Women. To do so, I tried a loop:

for i in df["female"]:   
    if i == 0:
        g.set_titles(col_template = "Men")
    else:
        g.set_titles(col_template = "Women")

But it yields Men on both plots. What's wrong?

1 Answers

One approach uses g.axes[row, column].set_title(...).

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

np.random.seed(1234)
df = pd.DataFrame({"exper": np.random.randint(1, 11, 50),
                   "wage": np.random.randint(100, 200, 50),
                   "female": np.random.randint(0, 2, 50)})
df["wage"] += df["exper"] * 10
g = sns.lmplot(x="exper", y="wage", hue="female", col="female", data=df, sharey=True)
g.axes[0, 0].set_title("Male")
g.axes[0, 1].set_title("Female")
g.axes[0, 1].tick_params(labelleft=True) # to set the ticks when sharey=True
g.fig.tight_layout()
plt.show()

lmplot with changed titles

Another approach is to temporarily rename 0 to male and 1 to female. And also change the column name from female to gender:

df1 = df.replace({"female": {0: "male", 1: "female"}}).rename(columns={"female": "gender"})
g = sns.lmplot(x="exper", y="wage", hue="gender", col="gender", data=df1, sharey=True)
g.axes[0, 1].tick_params(labelleft=True)
g.fig.tight_layout()
plt.show()

renaming the elements to change an lmplot

Related