【问题标题】:Legend for matplotlib plot not showing upmatplotlib 图的图例未显示
【发布时间】:2020-12-16 13:39:14
【问题描述】:

我正在尝试为所附图像绘制图例,但无法使用以下查询绘制图例,有人可以帮我解决这个问题吗?

#Predicted Labels on PCA
pcadf = pd.DataFrame(preprocessed_data)
pcadf["kmeans"] = pipe["clusterer"]["kmeans"].labels_
pcadf.columns = ['component_1', 'component_2', 'kmeans']

x = pcadf['component_1'].values
y = pcadf['component_2'].values

Cluster = pcadf["kmeans"].values
fig = plt.figure(figsize=(10,5))

ax = fig.add_subplot(111)
scatter = ax.scatter(x,y,c=Cluster,s=50)
ax.legend()
fig.savefig('KMeans_Cluster.png', bbox_inches='tight', dpi=1200)

【问题讨论】:

    标签: python matplotlib plot legend


    【解决方案1】:

    this matplotlib help page for the 2 options。您可以遍历不同的标签,或者使用 PathCollection 的 legend_elements() ,下面我使用第二个选项的示例:

    from sklearn.decomposition import PCA
    import matplotlib.pyplot as plt
    import seaborn as sns
    from sklearn.cluster import KMeans
    from sklearn.preprocessing import StandardScaler
    
    iris = sns.load_dataset('iris')
    df = StandardScaler().fit_transform(iris.iloc[:,:4])
    
    pcadf = PCA(n_components=2).fit_transform(df)
    pcadf = pd.DataFrame(pcadf,columns = ['component_1','component_2'])
    pcadf["kmeans"] = KMeans(n_clusters=2).fit_predict(df)
    
    #Cluster = pcadf["kmeans"].values
    fig = plt.figure(figsize=(10,5))
    ax = fig.add_subplot(111)
    ax.scatter(pcadf['component_1'],pcadf['component_2'],c=pcadf['kmeans'],s=50)
    legend1 = ax.legend(*scatter.legend_elements(),
                        loc="lower left", title="Clusters")
    ax.add_artist(legend1)
    

    【讨论】:

      猜你喜欢
      • 2023-01-18
      • 2020-12-09
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 1970-01-01
      • 2018-05-12
      • 2016-12-29
      相关资源
      最近更新 更多