如何将带有 ID 标签的图例添加到我的代码中

How to add legend with labels of IDs to my code

我有 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 的图例,请帮忙

因为我没有你的数据,所以我现在无法在绘图中测试它,但我认为问题出在没有将 label 参数传递给 plt.plot 即:

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