matplotlib - 如何根据分类变量将标题设置为 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, 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()
另一种方法是临时重命名0
为male
和。并将列名从更改为:1
female
female
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()
推荐阅读
- javascript - 自动装卸元件
- python - 如何将对象类型映射到具有大型数据集的 pandas.DataFrame 中的 int64
- javascript - 如何检测OLED显示器?
- excel - 如何向下循环运行直到右侧的单元格为空 - VBA excel
- c# - C# 中是否有与 IsNullOrEmpty 相反的内容
- java - 使用递归方法对数组进行排序
- r - 将 XML 文档转换为 R 数据帧,其中子节点都具有相同的名称并使用子节点进行标识
- ios - Stripe iOS:我无法使用卡 ID 创建费用
- vue.js - 如何使用 vue-router 将活动链接保持在非精确路由中
- swift3 - 将 NSCalendar 更新为 Swift3