【问题标题】:Different title for each subplot in 2 x 2 Seaborn2 x 2 Seaborn 中每个子图的不同标题
【发布时间】:2020-05-16 13:01:26
【问题描述】:

我正在尝试显示 2 x 2 Seaborn 直方图。

我想为每个子图使用不同的标题。

这运行没有错误,并创建了所需的 2 x 2 子图矩阵,但所有四个子图都具有相同的标题(“标题”列表中的最后一项):

titles = ['SAT Participation Rates 2017 Distribution',
          'ACT Participation Rates 2017 Distribution',
          'SAT Participation Rates 2018 Distribution',
          'ACT Participation Rates 2018 Distribution']

cols = ['sat_participation_17',
        'act_participation_17',
        'sat_participation_18',
        'act_participation_18']

f, axes = plt.subplots(2, 2, figsize=(10, 10))
for ax, feature in zip(axes.flat, df[cols]):
    sns.distplot(df[feature], bins=8, kde=False, hist_kws={'edgecolor': 'black'}, ax=ax)
    ax.set_xlabel('Participation Rate')
    ax.set_ylabel('Frequency')
    for title in titles:
        ax.set_title(title)

plt.show()

【问题讨论】:

    标签: python-3.x matplotlib seaborn


    【解决方案1】:

    试试这个:

    count = 0
    for ax, feature in zip(axes.flat, df[cols]):
        sns.distplot(df[feature], bins=8, kde=False, hist_kws={'edgecolor': 'black'}, ax=ax)
        ax.set_xlabel('Participation Rate')
        ax.set_ylabel('Frequency')
        ax.set_title(titles[count])
        count+=1
    

    您的代码中的问题是内部 for 循环在每次外部循环迭代时重复,因此标题始终设置为列表中的最后一项 titles

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 2016-10-21
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多