[Python] How can I use a loop to make this faster?

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

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

    Continue reading...

Compartilhe esta Página