如何在散点图例中显示每个标签的数量?

How to show the number of each label in scatter legend?

我想制作一个由两部分组成的图例,第一部分是标签的名称,第二部分是标签对应的编号,例如: 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()

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

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