[Python] Trying to save Matplotlib plots with data subsets in a for-loop, but plots are not...

Discussão em 'Python' iniciado por Stack, Abril 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using the iris dataset as an example, because my real dataset has almost 100K entries. I want to save each individual plot with its own subset of species data, but when I run my code, they plot on top of each other.

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

    iris = sns.load_dataset('iris')

    species_sum = iris['species'].value_counts().rename_axis('species').reset_index(name='counts')

    for row in range(0, len(species_sum)):
    species = species_sum['species'].iloc[row]
    print(species)
    species_data = iris.loc[iris['species'] == species]

    species_plot = iris[iris['species'] == species]
    xerror = [species_plot['sepal_length']*0.3, species_plot['sepal_length']*0.5]

    plt.errorbar(x=species_plot['sepal_length'], y=species_plot['petal_length'], xerr=xerror, fmt='o')
    plt.xlabel('Sepal L')
    plt.ylabel('Petal L')
    plt.savefig(species+'.png')


    I don't want to use plt.show() if possible. Resulting image

    Continue reading...

Compartilhe esta Página