How to add map with cluster points with geopandas and contextily

182 views Asked by At

I'm new to geopandas and contextily and would like to understand how it works better. I have some geometry points to be plotted that have been clustered. On top of that I would like to add a map below it.

I have done this to generate my clusters.

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_

Then this is where i get stuck trying to plot the cluster points AND the background map together.

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()

Basically I would like to put the bottom map 'sg' onto my plot.

enter image description here

I have tried add_basemap but can't seem to get it working. Not very familiar with this, any advice?

1

There are 1 answers

0
Ku9feld On

Firstly, create ax and fig, and use ax like parameters in code:

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()