英文:
Different X Labels for Different Variables
问题
我有两个数据框,分别是 t1
和 t2
。我想要使用 for 循环绘制 seaborn 图,每个变量都并排显示。我能够实现这一点,但当我尝试设置自定义的 x 标签时失败了。我如何在 for 循环中使用 set_xlabel
?
data1 = {
'var1': [1, 2, 3, 4],
'var2': [20, 21, 19, 18],
'var3': [5, 6, 7, 8]
}
data2 = {
'var1': [5, 2, 3, 5],
'var2': [21, 18, 3, 11],
'var3': [1, 9, 3, 6]
}
t1 = pd.DataFrame(data1)
t2 = pd.DataFrame(data2)
xlabel_list = ["new_var1", "new_var2", "new_var3"]
def fun1(df1, df2, numvar, new_label):
plt.tight_layout()
fig, ax = plt.subplots(1, 2)
sns.kdeplot(data=df1[numvar], linewidth=3, ax=ax[0])
sns.kdeplot(data=df2[numvar], linewidth=3, ax=ax[1])
ax[0].set_xlabel(new_label, weight='bold', size=10)
ax[1].set_xlabel(new_label, weight='bold', size=10)
for col, new_label in zip(t1.columns, xlabel_list):
fun1(df1=t1, df2=t2, numvar=col, new_label=new_label)
英文:
I have two data frames t1
and t2
. I want a seaborn plot where it plots side by side for every variable using the for loop. I was able to achieve this but I fail when I try to set the customized x labels. How do I incorporate set_xlabel
in to the for loop?
data1 = {
'var1': [1, 2, 3, 4],
'var2': [20, 21, 19, 18],
'var3': [5, 6, 7, 8]
}
data2 = {
'var1': [5. 2. 3. 5],
'var2': [21, 18, 3, 11]
'var3': [1, 9, 3, 6]
}
t1 = pd.DataFrame(data1)
t2 = pd.DataFrame(data2)
xlabel_list = ["new_var1", "new_var2", "new_var3"]
def fun1(df1, df2, numvar, new_label):
plt.tight_layout()
fig, ax = plt.subplots(1, 2)
sns.kdeplot(data = df1[numvar], linewidth = 3, ax=ax[0])
sns.kdeplot(data = df2[numvar], linewidth = 3, ax=ax[1])
ax[0].set_xlabel(new_label, weight='bold', size = 10)
ax[1].set_xlabel(new_label, weight='bold', size = 10)
for col in t1.columns: # how to incorporate the new_label parameter in the for loop along with col?
fun1(df1 = t1, df2 = t2, numvar = col, new_label??)
答案1
得分: 1
使用 zip
:
for col, new_label in zip(t1.columns, xlabels_list):
英文:
Use zip
:
for col, new_label in zip(t1.columns, xlabels_list):
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论