【问题标题】:Seaborn plots in a nested for-loop嵌套 for 循环中的 Seaborn 绘图
【发布时间】:2020-12-14 21:41:57
【问题描述】:

我正在尝试遍历州和月份列表,以按月绘制列表中每个州的分数分布。

期望的结果是每个州的分数分布在其自己的图表上按月表示。因此,每个州图应该有两条线(按月 1 和月 2 分布所述州的分数)。

下面是我的代码的表示。

列表是这样创建的:

state_list = df['StoreStateName'].tolist()

states = set(state_list)

months = [
         '2020-11'
         ,'2020-12'
         ]

然后我尝试遍历这两个列表来创建图:

plt.figure(figsize = (18,28))
nrow = 10
ncol = 5
i = 1
for state in states:
    temp1 = df[df['StoreStateName'] == state]
    for month in months:
        temp2 = temp1[temp1['Month'] == month] 
    plt.grid()
    plt.subplot(nrow, ncol, i)
    plt.title(state) 
    sns.distplot(a=temp2['Score'], hist=False, label=month)
    plt.legend()
    i += 1
plt.tight_layout()
plt.show()

当我这样做时,输出看起来像:

第一个循环似乎正在运行,但子图缺少 11 月的分布。

任何想法将不胜感激,谢谢!

【问题讨论】:

    标签: python-3.x for-loop plot seaborn


    【解决方案1】:

    我想通了。原来我的代码有问题。

    这是解决我的问题的代码:

    plt.figure(figsize = (18,28))
    nrow = 10
    ncol = 5
    i = 1
    for state in states:
        temp = df[(df['StoreStateName'] == state)]
        plt.subplot(nrow, ncol, i)
        plt.grid()
        plt.title(state) 
        for month in months:
            temp2 = temp[(temp['Month'] == month)] 
            sns.distplot(a=temp2['Score'], hist=False, label=month)
            plt.legend().remove()
        i += 1
    plt.tight_layout()
    plt.legend(loc=4, bbox_to_anchor=(2.0, 0.5), prop={'size': 18})
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-07-24
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多