首页 > 解决方案 > 如何根据分类变量将标题设置为 lmplots?

问题描述

我需要根据定性变量(性别)绘制两个定量变量的 sns lmplot。当我按如下方式添加 hue 和 col 参数时:

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

一切都解决了。然而,我不想将每个情节命名为女性 = 0 和女性 = 1,而是将它们命名为男性和女性。为此,我尝试了一个循环:

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

但它在两个情节上都产生了男人。怎么了?

标签: matplotlibplotclassificationseaborn

解决方案


一种方法使用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

另一种方法是临时重命名0male和。并将列名从更改为:1femalefemalegender

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

重命名元素以更改 lmplot


推荐阅读