pythonloopsvisualization

How can I use a loop to make this faster?


I'm trying to plot these scatterplots in a figure with a loop. I'm using matplotlib (plt) and seaborn (sns).


plt.subplot(2, 3, 1)
sns.scatterplot(data = chile, x = 'Year', y = 'Life expectancy at birth (years)')
plt.title('Chile')

plt.subplot(2, 3, 2)
sns.scatterplot(data = china, x = 'Year', y = 'Life expectancy at birth (years)')
plt.title('China')

plt.subplot(2, 3, 3)
sns.scatterplot(data = germany, x = 'Year', y = 'Life expectancy at birth (years)')
plt.title('Germany')

plt.subplot(2, 3, 4)
sns.scatterplot(data = mexico, x = 'Year', y = 'Life expectancy at birth (years)')
plt.title('Mexico')

plt.subplot(2, 3, 5)
sns.scatterplot(data = usa, x = 'Year', y = 'Life expectancy at birth (years)')
plt.title('United States of America')

plt.subplot(2, 3, 6)
sns.scatterplot(data = zimbabwe, x = 'Year', y = 'Life expectancy at birth (years)')
plt.title('Zimbabwe')

plt.subplots_adjust(wspace = 0.5, hspace = 0.5)
plt.show()
plt.clf()

My figure

I tried looping through a list of my data, but it just made a new figure and plotted the graph in the first position.

countries = [chile, china, germany, mexico, usa, zimbabwe]

for country in countries:
    plot_number = 1
    plt.subplot(2, 3, plot_number)
    sns.scatterplot(data = country, x = 'Year', y = 'Life expectancy at birth (years)')
    plot_number += 1
    plt.show()
    plt.clf()

Solution

  • On each iteration of your loop, plot_number is set to 1, so incrementing it isn't going to do anything. Try moving plot_number = 1 to outside of the for loop:

    countries = [chile, china, germany, mexico, usa, zimbabwe]
    
    plot_number = 1
    for country in countries:
        plt.subplot(2, 3, plot_number)
        sns.scatterplot(data = country, x = 'Year', y = 'Life expectancy at birth (years)')
        plot_number += 1
    
    # needs to be outside the loop otherwise you'll create 6 different figures 
    plt.show()
    # needs to be outside the loop otherwise you'll clear the figure each time 
    plt.clf()