简体   繁体   中英

Figure overlaps while adding subplot using for loop

I am trying to plot three data frames in three columns using matplpotlib. I am plotting each column of a DF as a subplot in the respective column of the figure. But the plot seems to overlap with each other. Not sure what is going wrong. Please help me find the issue. Thanks.

I added the code below I tried to achieve what I mentioned above. I did not define a number of rows and columns in subplot since I wanted to create based on the number of columns in DF. Then I used add_subplot function to add each one them in for loop. But subplots are overlapping in the output. I tried fig.tightlayout based on suggestions from other post but I got UserWarning: tight_layout not applied: a number of rows in subplot specifications must be multiples of one another

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')

在此处输入图像描述

Based on the comment provided by @ImportanceOfBeingErnest, I modified my code as below and I got the expected plot. This way I am customizing/adding a subplot to individuation positions. This answer might be helpful for people looking for plotting subplots by looping over the data and ass the plot in the required position.

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')

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM