[英]Make legend correspond to colors of scatter points in matplotlib
我有一個情節,我通過scikit-learn中的KMeans算法生成。 簇對應於不同的顏色。 這是情節,
我需要一個這個圖的圖例,它對應於圖中的簇編號。 理想情況下,圖例應顯示群集的顏色,標簽應為群集編號。 謝謝。
編輯:我認為我應該放一些代碼,因為人們正在貶低這個
from sklearn.cluster import KMeans
km = KMeans(n_clusters=20, init='random')
km.fit(df) #df is the dataframe which contains points as coordinates
labels = km.labels_
plt.clf()
fig = plt.figure()
ax = fig.add_subplot(111, axisbg='w', frame_on=True)
fig.set_size_inches(18.5, 10.5)
# Plot the clusters on the map
# m is a basemap object
m.scatter(
[geom.x for geom in map_points],
[geom.y for geom in map_points],
20, marker='o', lw=.25,
c = labels.astype(float),
alpha =0.9, antialiased=True,
zorder=3)
m.fillcontinents(color='#555555')
plt.show()
我能夠使傳奇符合顏色。 關鍵是對Rutger Kassies提到的數據中的每個類別使用多個散點圖。
這是代碼:
import numpy as np
import matplotlib.pyplot as plt
# Setting various plot properties
plt.clf()
fig = plt.figure()
ax = fig.add_subplot(111, axisbg='w', frame_on=True)
fig.set_size_inches(18.5, 10.5)
# Creating a discrete colorbar
colors = plt.cm.rainbow(np.linspace(0, 1, 20))
current_plot_range = 0
previous_plot_range = 0
for i,c in enumerate(colors):
previous_plot_range += current_plot_range
current_plot_range = labels[labels==i].size
m.scatter(
[geom.x for geom in map_points[
previous_plot_range:previous_plot_range+current_plot_range]],
[geom.y for geom in map_points[
previous_plot_range:previous_plot_range+current_plot_range]],
20, lw=.25, marker='o',color = c, label=i, alpha =0.9, antialiased=True,
zorder=3)
plt.legend()
m.fillcontinents(color='#555555')
結果看起來像這樣:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.