微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何根据分类变量为lmplots设置标题?

如何解决如何根据分类变量为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")

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

解决方法

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

另一种方法是将 0 临时重命名为 male,将 1 临时重命名为 female。并将列名从 female 更改为 gender

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

renaming the elements to change an lmplot

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。