【问题标题】:How to show the number of each label in scatter legend?如何在散点图例中显示每个标签的数量?
【发布时间】:2021-10-09 11:59:09
【问题描述】:

我想做一个由两部分组合而成的图例,第一个是标签的名称,第二个是标签对应的编号,例如: 0:50; 1:50; 2:50

现在我的代码是这样的,我厌倦了通过 Counter 函数添加它的数量,但是,它显示错误: 只能将元组(不是“str”)连接到元组

import matplotlib.pyplot as plt
from sklearn import datasets
from collection import Counter
iris = datasets.load_iris()
X = iris.data
y = iris.target
df = pd.DataFrame(X, columns = iris.feature_names)

fig, ax = plt.subplots(figsize=(12,8))
points = ax.scatter(df.values[:,0], 
    df.values[:,1],
    c = y)
legend1 = ax.legend(*points.legend_elements() +':' + list(Counter(y).values()), loc = "lower left",title = 'clusters')  
#ax.add_artist(legend1)
#handles, labels = points.legend_elements(prop = 'sizes')
#legend2 = ax.legend(handles, labels, loc='upper right')
plt.show()

【问题讨论】:

    标签: python matplotlib scatter-plot


    【解决方案1】:

    由于图例的元素被检索,我们将处理检索到的标签并将值连接到一个字符串中。然后,您可以将其用作图例。

    import matplotlib.pyplot as plt
    from sklearn import datasets
    from collections import Counter
    import pandas as pd
    
    iris = datasets.load_iris()
    X = iris.data
    y = iris.target
    df = pd.DataFrame(X, columns = iris.feature_names)
    
    fig, ax = plt.subplots(figsize=(12,8))
    points = ax.scatter(df.values[:,0], 
        df.values[:,1],
        c = y)
    # create labels and handles
    labels = ['{}:{}'.format(l,t) for l,t in zip(points.legend_elements()[1], list(Counter(y).values()))]
    handles = [points.legend_elements()[0][0],points.legend_elements()[0][1],points.legend_elements()[0][2]]
    legend1 = ax.legend(handles, [labels[0],labels[1],labels[2]], loc = "lower left",title = 'clusters')  
    
    plt.show()
    

    【讨论】:

    • 或者只是handles, _ = points.legend_elements(): labels = [f'{item}: {count}' for item, count in Counter(y).items()]: ax.legend(handles, labels, ...)
    • @JohanC 评论中的代码很酷。感谢您的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    相关资源
    最近更新 更多