[英]Redundant Legends: Matplotlib
我的散點圖 plot 有多余的圖例。 這是我的 plot 的圖像。
在這個問題上,我已經在 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)
在這里,您給彩色點一個 label 'cluster' + str(label)
即使這樣的 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.