简体   繁体   English

matplotlib plot 的图例未显示

[英]Legend for matplotlib plot not showing up

I am trying to plot legends for the attached image and I am unable to plot legend with my below query, Could someone please help me resolve this?我正在尝试为附加图像添加 plot 图例,但我无法通过以下查询获得 plot 图例,有人可以帮我解决这个问题吗?

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

在此处输入图像描述

See this matplotlib help page for the 2 options .有关2 个选项,请参阅此 matplotlib 帮助页面 You either loop through the different labels, or use the PathCollection's legend_elements(), and below I use an example for the 2nd option:您可以遍历不同的标签,或者使用 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)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM