Skip to content
Advertisement

Creating multiple plots with for loop?

I have a dictionary of dataframes where the key is the name of each dataframe and the value is the dataframe itself.

I am looking to iterate through the dictionary and quickly plot the top 10 rows in each dataframe. Each dataframe would have its own plot. I’ve attempted this with the following:

for df in dfs:
    data = dfs[df].head(n=10)
    sns.barplot(data=data, x='x_col', y='y_col', color='indigo').set_title(df) 

This works, but only returns a plot for the last dataframe in the iteration. Is there a way I can modify this so that I am also able to return the subsequent plots?

Advertisement

Answer

By default, seaborn.barplot() plots data on the current Axes. If you didn’t specify the Axes to plot on, the latter will override the previous one. To overcome this, you can either create a new figure in each loop or plot on a different axis by specifying the ax argument.

import matplotlib.pyplot as plt


for df in dfs:
    data = dfs[df].head(n=10)
    plt.figure() # Create a new figure, current axes also changes.
    sns.barplot(data=data, x='x_col', y='y_col', color='indigo').set_title(df) 
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement