Home > Software engineering >  How to create several plots within a for loop?
How to create several plots within a for loop?

Time:05-08

I have the following Python code:

for key in my_dict:
    Sc = StandardScaler()
    X = Sc.fit_transform(my_dict[key])
    pca = PCA(2)
    pca_data = pd.DataFrame(pca.fit_transform(X),columns=['PC1','PC2'])
    kmeans = KMeans(n_clusters=2).fit(X)
    pca_data['cluster'] = pd.Categorical(kmeans.labels_)
    sns.scatterplot(x="PC1",y="PC2", data=pca_data)

I am iterating over a dictionary containing 40 dataframes and I want to plot 40 scatterplots based on the particular dataframes. However, after the for loop finished, it just plots one scatterplot with all the data agglomerated. But I want to plot a scatterplot for every dataframe in the dictionary. How can I plot a scatterplot for every "run of the loop"?

CodePudding user response:

You need to create a figure for each by calling plt.figure()

  • Related