Search code examples
python-3.xmatplotlibgeopandascartopy

Why can't one set to "False" specific axis ticklabels (ex: xlabels_top, ylabels_right) from a cartopy-geopandas plot?


I am having serious difficulties in setting to False the xlabels_top and ylabels_right from my Geopandas plot.

This geopandas plot is made inside a Geoaxes subplot created with PlateCarree projection from Cartopy library.

My geopandas Geodataframe is in SIRGAS 2000 (units: degrees), EPSG: 4989. Therefore I created a Geodetic Globe object from the cartopy library.

Here is a code snippet:

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

Geopandas_DF = gpd.read_file('my_file.shp')

# setting projection and Transform
Projection=ccrs.PlateCarree()
Transform = ccrs.Geodetic(globe=ccrs.Globe(ellipse='GRS80'))

Fig, Ax = plt.subplots(1,1, subplot_kw={'projection': Projection})

Geopandas_DF.plot(ax=Ax, transform=Ax.transData)

Ax.gridlines(crs=Projection , draw_labels=True, linewidth=0.5, 
             alpha=0.4, color='k', linestyle='--')

Ax.xlabels_top = False nn# It should turn off the upper x ticks
Ax.ylabels_right = False # It should turn off the right y ticks
Ax.ylabels_left = True
Ax.xlines = True

Fig.show()

Here is a figure example. One can notice that the xticks from the upper axis and the yticks from the right axis have not been turned OFF (False).

Figure with xticks and yticks error

Therefore, I would like to know whether that is a problem between Cartopy and Geopandas, or am I doing something wrong in my code.


Solution

  • The labels belong to the gridliner instance not the axes, you can turn them off there by storing the gridliner returned by the gridlines method and setting top_labels, right_labels as in:

    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs
    import geopandas as gpd
    
    Geopandas_DF = gpd.read_file('my_file.shp')
    
    # setting projection and Transform
    Projection=ccrs.PlateCarree()
    Transform = ccrs.Geodetic(globe=ccrs.Globe(ellipse='GRS80'))
    
    Fig, Ax = plt.subplots(1,1, subplot_kw={'projection': Projection})
    
    Geopandas_DF.plot(ax=Ax, transform=Ax.transData)
    
    gl = Ax.gridlines(crs=Projection , draw_labels=True, linewidth=0.5, 
                      alpha=0.4, color='k', linestyle='--')
    
    # For Cartopy <= 0.17
    gl.xlabels_top = False
    gl.ylabels_right = False
    # For Cartopy >= 0.18
    # gl.top_labels = False
    # gl.right_labels = False
    
    Fig.show()