python - 冗余图例:Matplotlib
问题描述
关于这个问题,我已经在 StackOverflow 上检查了以下现有问题: matplotlib 中带有数组列数据的图例过多
尽管如此,它并没有帮助。我想我遇到了一个完全不同的问题。请告诉我如何解决这个问题。
这是我的代码:
import matplotlib.cm as cm
colors = cm.rainbow(np.linspace(0, 1, N_Clus))
cluster_labels_2 = list(range(1, N_Clus+1))
print("cluster_labels: ", cluster_labels_2)
# Create a figure
plt.figure(figsize=(15,8))
s=0
for color, label in zip(colors, np.asarray(cluster_labels_2).flatten()):
subset = WorkingDF2[WorkingDF2.Cluster == label]
for i in subset.index:
x=np.asarray(subset["Standardized COVID-19 Index"][i]).flatten()
y=np.asarray(subset["Standardized CSS Index"][i]).flatten()
plt.text(x, y, str(subset['Neighbourhood'][i]), rotation=25)
s += 1
plt.scatter(x, y, c=np.array([color]), label='cluster'+str(label),alpha=0.5)
plt.legend(loc='lower right', fontsize=15)
plt.xlabel('Standardized COVID-19 Index', fontsize=18)
plt.ylabel('Standardized CSS Index', fontsize=18)
plt.title("[Hierarchical Clustering: {} Cluster] \n
Mapping of Non-Outlier Neighbourhoods \n
onto Standardized CSS-COVID19 Indices Space \n
".format(N_Clus), fontsize=18)
print('# of Neighbours: ', s)
解决方案
问题来自于线
plt.scatter(x, y, c=np.array([color]), label='cluster'+str(label),alpha=0.5)
'cluster' + str(label)
在这里,即使这样的标签已经存在,您也可以给彩色点一个标签,因此plt.legend()
将创建许多相同的图例元素。如果它不是新的,我会跟踪以前的标签并将当前情节的一个设置为None
,以便plt.legend()
忽略它。
请注意,您的命名选择可能会有些混乱,因为 matplotlib 使用“标签”作为出现在图例中的曲线的名称,而您将其用作簇编号。我们可以叫它cluster_number
吗?
这是实现:
import matplotlib.cm as cm
colors = cm.rainbow(np.linspace(0, 1, N_Clus))
cluster_labels_2 = list(range(1, N_Clus+1))
print("cluster_labels: ", cluster_labels_2)
# Create a figure.
plt.figure(figsize=(15, 8))
s=0
clusters_already_in_the_legend = []
for color, cluster_number in zip(colors, np.asarray(cluster_labels_2).flatten()):
subset = WorkingDF2[WorkingDF2.Cluster == cluster_number]
for i in subset.index:
x = np.asarray(subset["Standardized COVID-19 Index"][i]).flatten()
y = np.asarray(subset["Standardized CSS Index"][i]).flatten()
plt.text(x, y, str(subset['Neighbourhood'][i]), rotation=25)
s += 1
# Keeping track of the labels so that we don't legend them multiple times.
if cluster_number not in clusters_already_in_the_legend:
clusters_already_in_the_legend.append(cluster_number)
label = f"Cluster {cluster_number}"
else:
label = None
plt.scatter(x, y, c=np.array([color]), label=label, alpha=0.5)
plt.legend(loc='lower right', fontsize=15)
plt.xlabel('Standardized COVID-19 Index', fontsize=18)
plt.ylabel('Standardized CSS Index', fontsize=18)
plt.title("[Hierarchical Clustering: {} Cluster] \n
Mapping of Non-Outlier Neighbourhoods \n
onto Standardized CSS-COVID19 Indices Space \n
".format(N_Clus), fontsize=18)
print('# of Neighbours: ', s)
推荐阅读
- apache-nifi - 如何将自定义属性添加到 AttributesToJSON?
- kdb - 可靠地解析/应用函数到 kdb 中的表和字典
- python - PyQt5 - 获取当前窗口状态(最大化与否)
- android - TextInputLayout 在焦点上更改开始图标的颜色
- java - 如何在java中将字符串转换为json字符串和对象
- powershell - Powershell:尽管我的路径很短,但 Get-ChildItem 抛出“路径太长”错误
- android - Android - 绑定适配器无法加载文本
- asp.net-core - 带有标签助手 asp.net core 3.1 的表单验证不显示为红色
- java - Autosize = uniform 只缩小文本以适应,不增加大小
- android - Activity 覆盖状态栏