如何使用 geopandas 和上下文添加带有聚类点的地图

问题描述 投票:0回答:1

我对 geopandas 和上下文都很陌生,想了解它如何更好地工作。我有一些要绘制的已聚类的几何点。最重要的是,我想在它下面添加一张地图。

我这样做是为了生成我的集群。

from sklearn.preprocessing import StandardScaler

# Scale the latitude and longitude columns
scaler = StandardScaler()
mrt[['longitude', 'latitude']] = scaler.fit_transform(mrt[['latitude', 'longitude']])


from sklearn.cluster import KMeans

# Specify the number of clusters
num_clusters = 5

# Initialize the KMeans model
kmeans = KMeans(n_clusters=num_clusters)

# Fit the model to the data
kmeans.fit(mrt[['longitude', 'latitude']])

# Get the cluster labels for each data point
cluster_labels = kmeans.labels_

这就是我在尝试将聚类点和背景图绘制在一起时陷入困境的地方。

import matplotlib.pyplot as plt

# Plot the data points with their cluster labels
plt.scatter(mrt['longitude'], mrt['latitude'], c=cluster_labels)
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.title('Clustering of Geo Location Coordinates')

sg = ctx.Place("Singapore", source=ctx.providers.OpenStreetMap.Mapnik)
x = plt.show()
y = sg.plot()

基本上我想将底部地图“sg”放到我的地块上。

enter image description here

我尝试过 add_basemap 但似乎无法让它工作。对这个不太熟悉,有什么建议吗?

python matplotlib geopandas contextily
1个回答
0
投票

首先创建ax和fig,并在代码中使用类似ax的参数:

fig,ax = plt.subplots(1,1,figsize=(10,12))

# Plot the data points with their cluster labels
plt.scatter(mrt['longitude'], mrt['latitude'], c=cluster_labels,ax=ax)
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.title('Clustering of Geo Location Coordinates')

sg = ctx.Place("Singapore", source=ctx.providers.OpenStreetMap.Mapnik,ax=ax)
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.