How to draw Scatter plot on top of background using Basemap Python

Viewed 12461

I am trying to plot a scatter plot on a background using basemap. But it's overwriting the background. How do I retain the background?

I am using this code

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='c')

m.bluemarble()

x, y = m(list(longitude), list(latitude))
plt.scatter(x,y,1,marker='o',color='Red')
plt.show()

But as soon as I run the scatter plot, its overwriting background image. How can I overlay the scatter plot on the image.

3 Answers

This is how to plot a series of points on top of a raster map. Note that the bluemarble image is huge, so a full scale (1.0 or default) plot of it should be avoided. The code is based on yours.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

# make up some data for scatter plot
lats = np.random.randint(-75, 75, size=20)
lons = np.random.randint(-179, 179, size=20)

fig = plt.gcf()
fig.set_size_inches(8, 6.5)

m = Basemap(projection='merc', \
            llcrnrlat=-80, urcrnrlat=80, \
            llcrnrlon=-180, urcrnrlon=180, \
            lat_ts=20, \
            resolution='c')

m.bluemarble(scale=0.2)   # full scale will be overkill
m.drawcoastlines(color='white', linewidth=0.2)  # add coastlines

x, y = m(lons, lats)  # transform coordinates
plt.scatter(x, y, 10, marker='o', color='Red') 

plt.show()

The resulting plot:

enter image description here

I realize it's an old question but in case anyone comes here with the same problem as I did.

The trick is to give a higher zorder for the scatter plot than for the .bluemarble().

m.scatter(x, y, 10, marker='o', color='Red', zorder=3)

More info here: https://matplotlib.org/3.1.0/gallery/misc/zorder_demo.html

I'm not entirely sure what you mean by "overwriting the background". When you use plt.scatter(), it will plot the points over the map, so it will display the points over the background.

Just based off the code provided, I think you're issue here is m(list(longitude), list(latitude)).

If you have multiple points in a list, you want to loop over them.

lats = [32, 38, 35]
lons = [-98, -79, -94]
x, y = m(lons, lats)

for i in range(len(lats)):
   plt.scatter(x, y, marker = 'o')

If it's only one single point,

lat, lon = 32, -92
x, y = m(lon, lat)
plt.scatter(x, y, marker = 'o')

The styling of the points can be found in the matplotlib documentation.

Related