Search code examples
pythonmatplotlibmatplotlib-basemapcartopy

Share x and y axis between subplots with map


I want to use sharex and sharey to sync zooming and clicking in two subplots.

Here's a simple code:

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature

proj = ccrs.LambertConformal(central_latitude=39,central_longitude=-95,
                            standard_parallels = (39, 39))

fig = plt.figure(figsize=(12,12))

ax1 = plt.subplot(2,2,1,projection = proj)
ax2 = plt.subplot(2,2,2,projection = proj,sharex=ax1, sharey=ax1)

ax1.coastlines()
ax2.coastlines()
ax1.add_feature(cfeature.STATES)
ax2.add_feature(cfeature.STATES)

ax1.set_extent([-100, -80, 20, 35], crs=ccrs.PlateCarree())
ax2.set_extent([-100, -80, 20, 35], crs=ccrs.PlateCarree())

lon, lat = -85, 25

ax1.scatter(lon,lat,transform=ccrs.PlateCarree())
ax2.scatter(lon,lat,transform=ccrs.PlateCarree())

plt.show()

But, the range of map is different: original After a little moving by the moving tool, it's same! move

Here's another example:

import matplotlib.pyplot as plt
import cartopy.crs as ccrs


proj = ccrs.PlateCarree()

ax1 = plt.subplot(1,4,1,projection = proj)
ax2 = plt.subplot(1,4,2,projection = proj,sharex=ax1, sharey=ax1)
ax3 = plt.subplot(1,4,3,projection = proj,sharex=ax1, sharey=ax1)
ax4 = plt.subplot(1,4,4,projection = proj,sharex=ax1, sharey=ax1)


for ax in [ax1,ax2,ax3,ax4]:
    ax.coastlines()
    gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, color='gray', alpha=0.5, linestyle='--')
    ax.set_extent([-105, -75, 25, 50], crs=ccrs.PlateCarree())

plt.show()

And, the result looks strange:

example_2


Solution

  • It's related to the version of matplotlib. After updating to 3.0.2, it works fine now.