Search code examples
pythonmatplotlibmetpy

How can I add the value in every point to a Contour Plot?


Right now I'm using matplotlib to generate contour plots of climatic variables. Now I wanted to add the numeric value on each point so that the final plot looks something like this:

Desired Plot

So, I was wondering if I could get some help on how I could display this values.

The code I currently use to make my plots is the following:

from matplotlib.cm import get_cmap
import numpy as np
from cartopy import crs
from cartopy.feature import NaturalEarthFeature
import matplotlib
import matplotlib.pyplot as plt
from netCDF4 import Dataset
import xarray as xr

from wrf import (getvar, interplevel, vertcross, 
                 CoordPair, ALL_TIMES, to_np,
                 get_cartopy, latlon_coords,
                 cartopy_xlim, cartopy_ylim)


lats, lons = latlon_coords(ctt)

cart_proj = get_cartopy(ctt)

fig = plt.figure(figsize=(12,9))
ax_ctt = fig.add_subplot(1,1,1,projection=cart_proj)

contour_levels = [-10, 0, 10, 20, 30, 40]
ctt_contours = ax_ctt.contourf(to_np(lons), to_np(lats), to_np(ctt),
                               contour_levels, cmap=get_cmap("Blues_r"),
                               transform=crs.PlateCarree())


cb_ctt = fig.colorbar(ctt_contours, ax=ax_ctt, shrink=.60)
cb_ctt.ax.tick_params(labelsize=9)

ax_ctt.set_xlim(cartopy_xlim(ctt))
ax_ctt.set_ylim(cartopy_ylim(ctt))
ax_ctt.gridlines(color="white", linestyle="dotted")

states = NaturalEarthFeature(category="cultural", scale="10m",
                             facecolor="none",
                             name="admin_1_states_provinces")
ax_ctt.add_feature(states, linewidth=0.2, edgecolor="black")
ax_ctt.coastlines('10m', linewidth=0.4)

plt.show()

Any insights in how to do this would be appreciated!


Solution

  • Currently, the easiest way to accomplish this would be to use MetPy's StationPlot class to plot the text values:

    from metpy.plots import StationPlot
    
    sp = StationPlot(ax_ctt, to_np(lons), to_np(lats),
        transform=ccrs.PlateCarree(), fontsize=14)
    sp.plot_parameter('C', to_np(ctt))