Hello! 😁
Your issue is that the plots are overlapping because you’re using the same figure for each iteration. To solve this problem, please follow these steps.
First, Create a New Figure. Inside your loop, call plt.figure()
to create an independent canvas for each species.
plt.figure()
Second, Plot the Data. Filter the data for the specific species and draw your plot (for example, using error bars).
Third, Save the Figure. Use plt.savefig()
to save the current figure to a file. It helps to include the species name in the filename for easy identification.
Finally, Close the Figure. Call plt.close()
to close the current figure. This prevents subsequent plots from being drawn on top of it.
plt.close()
Example Code
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(len(species_sum)):
species = species_sum['species'].iloc[row]
print(species)
species_data = iris.loc[iris['species'] == species]
# Create a new Figure
plt.figure()
xerror = [species_data['sepal_length'] * 0.3, species_data['sepal_length'] * 0.5]
plt.errorbar(
x=species_data['sepal_length'],
y=species_data['petal_length'],
xerr=xerror,
fmt='o'
)
plt.xlabel('Sepal L')
plt.ylabel('Petal L')
# Save the figure with the species name in the filename
plt.savefig(species + '.png')
# Close the figure to free memory and avoid overlap with the next iteration
plt.close()
Thx, Have a good one!