【问题标题】:Figure overlaps while adding subplot using for loop使用 for 循环添加子图时图形重叠
【发布时间】:2019-11-08 23:09:06
【问题描述】:

我正在尝试使用 matplpotlib 在三列中绘制三个数据框。 我将 DF 的每一列绘制为图中相应列中的子图。但情节似乎相互重叠。不知道出了什么问题。请帮我找出问题。谢谢。

我添加了下面的代码,我试图实现我上面提到的。我没有在 subplot 中定义行数和列数,因为我想根据 DF 中的列数来创建。然后我使用 add_subplot 函数将它们添加到 for 循环中。但是子图在输出中重叠。我根据其他帖子的建议尝试了 fig.tightlayout,但我得到了 UserWarning:tight_layout not applied: a number of rows in subplot specification must be multiple of each other

fig = plt.figure()

#looping through each DF in a dict
for df_count, df_name in enumerate(df_dict):
    df = df_dict[df_name]

    #looping through column in the DF
    for col_count, col in enumerate(df_dict[df_name]):
        if col != "VAR":
            print (col, col_count )
            ax = fig.add_subplot(col_count, df_count + 1, 1)
            ax.plot(df[col], df["CATEGORY"])

fig.tight_layout()
plt.savefig('foo.png')

【问题讨论】:

标签: python pandas matplotlib seaborn


【解决方案1】:

根据@ImportanceOfBeingErnest 提供的评论,我修改了我的代码,如下所示,得到了预期的情节。通过这种方式,我正在自定义/添加子图到个性化位置。这个答案可能有助于人们通过循环遍历数据并将绘图放置在所需位置来寻找绘制子图。

fig = plt.figure(figsize=(10,10))
subplot_count_a = 0
#looping through each DF in a dict
for df_count, df_name in enumerate(df_dict):
    subplot_count_a += 1
    subplot_count = subplot_count_a
    df = df_dict[df_name]
    #looping through column in the DF
    print(df_name)
    for col in df:
        if col != "VAR" and col != "CATEGORY":
            print (f"({col}, {len(df.columns) - 2}, {len(df_dict)} , {subplot_count})")
            ax = fig.add_subplot(len(df.columns) -2 , len(df_dict) , subplot_count)
            ax = sns.scatterplot(x=col, y="CATEGORY", hue="CATEGORY", data=df, legend=False)
            ax.set_ylabel('')    
            ax.set_xlabel('')
            subplot_count += 3
    fig.tight_layout()
    plt.savefig('foo.png')

【讨论】:

    猜你喜欢
    • 2020-07-21
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 2021-01-29
    相关资源
    最近更新 更多