【问题标题】:How to add legend with labels of IDs to my code如何将带有 ID 标签的图例添加到我的代码中
【发布时间】:2021-03-28 04:49:56
【问题描述】:

我有 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 Im 加上我得到这个的图例:

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

代码中没有错误,它正在运行,但我希望我的代码生成自动图例,其中包含从 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 的图例,请任何帮助

【问题讨论】:

  • 您没有在plt.plot() 中提供标签并为每一行绘制图例。
  • 谢谢回答,我只是不知道怎么加标签,每个房子都会有一个ID,可以从地块上知道每个房子的消费情况

标签: python python-3.x matplotlib cluster-analysis legend


【解决方案1】:

由于我没有您的数据,我现在无法在绘图中对其进行测试,但我认为问题出在没有将 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")

【讨论】:

  • 嗨@AghyadSkaif,很高兴听到这个消息!如果它完全回答了您的问题,您可以接受答案,它会通知所有人问题已解决:)
  • 我刚刚做了,抱歉我m new here and I dont 知道我应该做的所有步骤
猜你喜欢
  • 1970-01-01
  • 2019-05-29
  • 1970-01-01
  • 2019-03-26
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
  • 2020-07-12
  • 1970-01-01
相关资源
最近更新 更多