首页 > 解决方案 > 如何将带有 ID 标签的图例添加到我的代码中

问题描述

我有 25 座房屋的用电量,m doing K-Means clustering on the dataset that holds those houses. After importing the dataset, pre-processing it, and applying K-Means with K=2, I plotted the data but when I我正在添加我得到的图例:

没有发现带有标签的手柄放在图例中。

代码中没有错误并且它正在运行,但我希望我的代码生成自动图例,其中包含从 0 到 24 的每个房屋的 ID。

这是我绘制数据的代码:

plt.figure(figsize=(13,13))
import itertools 
marker = itertools.cycle(('+', 'o', '*' , 'X', 's','8','>','1','<')) 
for cluster_index in [0,1]:
    plt.subplot(2,1,cluster_index + 1)
    
    for index, row in data1.iterrows():
        if row.iloc[-1] == cluster_index:
            plt.plot(row.iloc[1:-1] ,marker = next(marker) , alpha=1)
        
        plt.legend(loc="right")
       
        
    plt.plot(kmeans.cluster_centers_[cluster_index], color='k' ,marker='o', alpha=1)
    ax = plt.gca()
    ax.tick_params(axis = 'x', which = 'major', labelsize = 10)  
    plt.xticks(rotation="vertical")
    plt.ylabel('Monthly Mean Consumption 2018-2019', fontsize=10)
    plt.title(f'Cluster {cluster_index}', fontsize=15)
    
plt.tight_layout()
plt.show()
plt.close()

我只想在输出图中有每个房子的 id 的图例,请帮助

标签: pythonpython-3.xmatplotlibcluster-analysislegend

解决方案


由于我没有您的数据,因此我现在无法在绘图中对其进行测试,但我认为问题出在没有将label参数传递给plt.plotie:

for index, row in data1.iterrows():
    if row.iloc[-1] == cluster_index:
        plt.plot(row.iloc[1:-1] ,marker = next(marker), alpha=1, label=index)
    
    plt.legend(loc="right")

推荐阅读