Search code examples
pythonmatplotlibcartopy

What is the correct way to get xticks and yticks values with Cartopy and Matplotlib?


Good evening, all !

Today I tried to put in place a system to plot automatically gridded data using python (3.5), matplotlib (2.2.3) and Cartopy (0.16), all under Windows 10. I would like to get xticks and yticks values (coordinates shown in a figure) and show them to the user (it is possible for him to set his own values). The problem is that the methods 'get_xticks()' and 'get_yticks()' seem to give weird results.

Here is an example code:

import numpy
import matplotlib.pyplot as plt
import cartopy

lon = numpy.arange(-180,180,1)
lat = numpy.arange(-90,90,1)
data = numpy.ones((len(lat), len(lon)))

ax = plt.subplot(1, 1, 1, projection=cartopy.crs.PlateCarree())
ax.pcolormesh(lon, lat, data, transform=cartopy.crs.PlateCarree(), cmap='jet')
ax.set_extent((-180,180,-90,90), cartopy.crs.PlateCarree())
ax.coastlines()

shp_file = cartopy.io.shapereader.natural_earth(resolution='110m', category='physical', name='land')
for land in cartopy.io.shapereader.Reader(shp_file).records():
    ax.add_geometries(land.geometry, cartopy.crs.PlateCarree(), facecolor='#e6e6e6')

gl = ax.gridlines(crs=cartopy.crs.PlateCarree(), draw_labels=True,
                  linewidth=1, color='black', alpha=1, linestyle='-')
gl.xlabels_top = True
gl.ylabels_left = True
gl.xlines = True
gl.ylines = True

plt.show()

print(gl.axes.get_xticks())
print(gl.axes.get_yticks())

Results of the previous are:

[-200. -150. -100.  -50.    0.   50.  100.  150.  200.] for X axis
[-100.  -75.  -50.  -25.    0.   25.   50.   75.  100.] for Y axis

I can't understand where Cartopy and Matplotlib are taking those values ... and as I just started to use Cartopy, I can't imagine its a bug ... I am used to work with Matplotlib to plot different kind of timeseries. But here, I am struggling seriously to understand what's going on and to find a solution.

So my question is simple, is there a simple way to get the xticks and yticks values as shown in the figure ?

Thanks a lot for your help !

Olivier

Update: I just add the figure we can obtain with the code I posted above. cartopy example


Solution

  • I'm not certain, but I think the clue is in the matplotlib.ticker.MaxNLocator object that gridliner defaults to using:

    print(gl.xlocator.tick_values(*ax.get_xlim()))
    print(gl.ylocator.tick_values(*ax.get_ylim()))
    

    gives

    [-180. -120.  -60.    0.   60.  120.  180.]
    [-100.  -80.  -60.  -40.  -20.    0.   20.   40.   60.   80.  100.]