I am trying to move from Basemap in python2 to cartopy in python3. However, I am finding it difficult to transform some Basemap code block to cartopy:
Basemap (python2.7)
from mpl_toolkits.basemap import Basemap
bmap = Basemap(projection='merc', resolution='c', llcrnrlon=-125, llcrnrlat=26, urcrnrlon=-56, urcrnrlat=46)
print bmap.makegrid(4, 4)[0]
[[-125. -102. -79. -56.]
[-125. -102. -79. -56.]
[-125. -102. -79. -56.]
[-125. -102. -79. -56.]]
print bmap.makegrid(4, 4)[1]
[[26. 26. 26. 26. ]
[33.23223798 33.23223798 33.23223798 33.23223798]
[39.91267019 39.91267019 39.91267019 39.91267019]
[46.00000132 46.00000132 46.00000132 46.00000132]]
cartopy (python 3.7)
import cartopy.crs as ccrs
mrc = ccrs.Mercator()
lons = np.array([-125, -56])
lats = np.array([26, 46])
width = 4
height = 4
projected_corners = mrc.transform_points(ccrs.PlateCarree(), lons, lats)
xs = np.linspace(
projected_corners[0, 0], projected_corners[1, 0], width)
ys = np.linspace(
projected_corners[0, 1], projected_corners[1, 1], height)
print(xs)
[-14248894.82153902 -6567849.95680314]
print(ys)
[2736034.98592771 6413524.59416364]
Note: I am trying to follow steps mentioned here using Mercator projection to get behavior similar to makegrid but the result does not match with Basemap as seen above.
The results are in good agreement if compared on the same basis (coordinate system). Here is the runnable code and the results:
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
mrc = ccrs.Mercator()
lons = np.array([-125, -56])
lats = np.array([26, 46])
width = 4
height = 4
projected_corners = mrc.transform_points(ccrs.PlateCarree(), lons, lats)
xs = np.linspace(projected_corners[0, 0], projected_corners[1, 0], width)
ys = np.linspace(projected_corners[0, 1], projected_corners[1, 1], height)
x2d, y2d = np.meshgrid(xs, ys)
ax = plt.axes(projection = mrc)
ax.coastlines()
ax.scatter(x2d, y2d)
ax.gridlines(draw_labels=True)
plt.show()
Output plot:
And the computation for coordinates (long, lat) of the grid points:
platecarr = ccrs.PlateCarree()
lon_lat_list = platecarr.transform_points(ccrs.Mercator(), xs, ys)
print(lon_lat_list)
[[-125. 26. 0. ]
[-102. 33.23738591 0. ]
[ -79. 39.91736844 0. ]
[ -56. 46. 0. ]]