Search code examples
pythoncartopy

Display latitude and longitude values on x and y axis


How can I add the latitude and longitude values on the x and y axis of my graph?

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


def main():
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
    ax.set_extent([-20, 60, -40, 45], crs=ccrs.PlateCarree())

    ax.add_feature(cfeature.LAND)

    plt.show()

main()

Solution

  • To draw grid and labels on the axes, you need to add this command (after ax.add_feature):

    ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True)
    

    and the plot should look like this:

    enter image description here

    Edit

    To enable more control on the components of the gridliners, set the the values [True / False] on them discretely as shown in the code below:

    gridliner = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True)
    gridliner.xlabels_top = True
    gridliner.xlabels_bottom = True
    gridliner.ylabels_left = True
    gridliner.ylabels_right = True
    gridliner.ylines = True  # you need False
    gridliner.xlines = True  # you need False