不同变量的不同X轴标签

huangapple go评论61阅读模式
英文:

Different X Labels for Different Variables

问题

我有两个数据框,分别是 t1t2。我想要使用 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):

huangapple
  • 本文由 发表于 2023年6月2日 02:55:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76384902.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定