Aaditya Ura
Aaditya Ura

Reputation: 12669

How to avoid overlapping last seaborn plot colors in new seaborn plots?

I am trying to generate different colour bulk plots for data, but it doesn't use all the colours while saving the figure.

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

total_ple = ['inferno', 'icefire_r', 'icefire', 'gray', 'gnuplot_r', 'gist_yarg_r', 'gist_stern', 'gist_heat_r', 'gist_heat', 'gist_gray', 'gist_earth', 'flare', 'crest_r', 'copper_r', 'coolwarm_r', 'cividis_r', 'cividis', 'YlGnBu_r', 'Spectral_r', 'Spectral', 'Set2', 'Set1', 
             'RdYlGn_r', 'RdYlBu_r', 'RdGy_r', 'RdBu_r', 'PuOr', 'PuBu_r', 'PuBuGn_r', 'PiYG', 'Paired', 'PRGn', 'Greys_r', 'GnBu_r', 'Dark2_r', 'Dark2', 'BrBG', 'Blues_r', 'Accent_r', 'viridis', 'tab10']


def bulk_plots(dfs_dict, ple="tab10", plot_name="default0"):

    plt.rcParams["figure.figsize"] = [20.0, 7.0]
    plt.rcParams.update(
        {
            "font.size": 22,
        }
    )

    sns.set_style("white")

    sns.set_context("talk", font_scale=0.8)
    for col_name, df_object in dfs_dict.items():
        sns.set_palette(ple)
        g = sns.distplot(df_object[col_name])

    sns.despine(left=True, bottom=True)

    plt.tick_params(axis="x", which="major", labelsize=10)
    plt.savefig(f"{plot_name}.pdf", bbox_inches="tight", dpi=350)

dummy_data

df_data1 = pd.DataFrame({'col_1': np.random.randint(0,100,[10000])})
df_data2 = pd.DataFrame({'col_2': np.random.randint(0,100,[10000])})

df_data  = {'col_1': df_data1, 'col_2': df_data2}

Calling:

for k in total_ple:
    
    bulk_plots(df_data,
               ple = k,
               plot_name = f'default_{k}')

In the folder, I see only 2-3 colours being used, but if I call plt.show() rather than plt.savefig, it shows all the colour plots in Jupiter's notebook.

How to save all color plots?

Upvotes: 1

Views: 366

Answers (1)

Zephyr
Zephyr

Reputation: 12496

When you create multiple plots in a loop, it is advisable to specify in which figure and axis to draw the plot. In you case, you can re-define a new figure and a new axis in each loop with matplotlib.pyplot.subplots and pass the axis to seaborn.distplot:

def bulk_plots(dfs_dict, ple="tab10", plot_name="default0"):

    plt.rcParams["figure.figsize"] = [20.0, 7.0]
    plt.rcParams.update(
        {
            "font.size": 22,
        }
    )

    sns.set_style("white")

    sns.set_context("talk", font_scale=0.8)

    fig, ax = plt.subplots()

    for col_name, df_object in dfs_dict.items():
        sns.set_palette(ple)
        g = sns.distplot(df_object[col_name], ax = ax)

    sns.despine(left=True, bottom=True)

    plt.tick_params(axis="x", which="major", labelsize=10)
    plt.savefig(f"folder/{plot_name}.pdf", bbox_inches="tight", dpi=350)

Upvotes: 1

Related Questions