代码之家  ›  专栏  ›  技术社区  ›  user2205916

python:动态生成seaborn图,然后并排显示结果?

  •  0
  • user2205916  · 技术社区  · 6 年前

    我试着制造出多个 seaborn 我的熊猫数据帧的数值变量的内核密度图。我把所有数字列的名字都列在一个列表里, numberCol 是的。现在,我可以 kdeplot 对于我显式命名的每个变量,如下所示:

    import seaborn as sbn
    sbn.set_style('whitegrid')
    sbn.kdeplot(np.array(df.v2), bw=0.5) # for pandas.core.frame.DataFrame input
    

    有没有更好的方法来遍历 数字控制 列表,生成 sbn.kdeplot 对于中的每个变量 数字控制 ,然后用比以下内容更聪明的内容并排显示:

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    # Here we create a figure instance, and two subplots
    fig = plt.figure(figsize = (20,20)) # width x height
    ax1 = fig.add_subplot(3, 3, 1) # row, column, position
    ax2 = fig.add_subplot(3, 3, 2)
    ax3 = fig.add_subplot(3, 3, 3)
    
    # We use ax parameter to tell seaborn which subplot to use for this plot
    sns.heatmap(data=subset1.corr(), ax=ax1, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12})
    sns.heatmap(data=subset2.corr(), ax=ax2, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12})
    sns.heatmap(data=subset3.corr(), ax=ax3, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12})
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Diziet Asahi    6 年前

    如果我明白你的问题,这应该能解决问题

    Ncols = 9
    cols = ['col_{:d}'.format(i) for i in range(Ncols)]
    df = pd.DataFrame(np.random.random(size=(1000,Ncols)),columns=cols)
    
    fig, axs = plt.subplots(3,3) # adjust the geometry based on your number of columns to plot
    for ax,col in zip(axs.flatten(), cols):
        sns.kdeplot(df[col], ax=ax)
    

    enter image description here