在底图上添加多个(集群)标签

时间:2018-08-29 11:53:02

标签: pandas label cluster-analysis k-means matplotlib-basemap

这是我的代码,用于在英国为我的数据集(分为2个群集)应用KMeans群集算法。在clusters = m.scatter(etc,..)行,我希望能够标记两个集群。同样,在行cog = m.scatter(etc,..)上,我想分别使用标签“ CoG群集1”和“ CoG群集2”。

我已经尝试了某种循环,但是它似乎仍然只绘制了1个标签。

enter image description here

import pandas as pd
from sklearn.cluster import KMeans
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10, 10))
m = Basemap(projection='lcc', resolution='h', 
        lat_0=54.7, lon_0=-3.36,
        width=0.7E6, height=1.2E6)

m.drawmapboundary(fill_color='white')
m.drawcoastlines()
m.drawcountries()

#load locations
X = pd.read_csv("123.csv")

lat = X['Latitude'].values
lon = X['Longitude'].values

#apply the KMeans Clustering Algorithm and plot clusters
km = KMeans(n_clusters=2, random_state=0, algorithm ='full')
km.fit(X)

# review the cluster labels, save them, and sort by cluster
X['cluster'] = km.labels_

# save the DataFrame of cluster centers
centers = X.groupby('cluster').mean()

# create a "colors" array for plotting
import numpy as np
cluster_colors = np.array(['green','blue'])
centroid_colors = np.array(['black','orange'])

# scatter plot colored by cluster (1=green, 2=blue)
clusters = m.scatter(lon, lat, latlon=True, c=cluster_colors[X.cluster], s=80, alpha=0.8,label="Cluster 2")

#plot centre of gravity for each cluster (unweighted)
cog = m.scatter(centers['Longitude'].values, centers['Latitude'].values, latlon=True, marker='s', alpha=0.8, s=200, c=centroid_colors[X.cluster],label="CoG Cluster 1")

plt.legend(frameon=True,facecolor='white',handles=[cog,clusters])

plt.show()

0 个答案:

没有答案