Search code examples
pythonmatplotlibplotvisualizationcartopy

How to change the interval of contours/colorbar in matplotlib to visualize temperature gradient in finer detail?


I am trying to visualize the temperature field of a dataset, and have attempted to do so by plotting it with matplotlib and cartopy. I have succeeded in creating a general picture, but there is one major flaw that I am trying to figure out how to correct. I want to make the contour interval much smaller (1 kelvin or 0.5 kelvin intervals) to properly visualize the minute details of the dataset. Right now, my figure looks like this:

Potential Temperature w/ inappropriate interval

You can see the general field, but the fine details are completely lost. How can I fix this situation, and see finer details in my temperature field.

Relevant code:

# FOR SINGLE PLOT ONLY

# Get WRF variables
theta_2m = getvar(ds, 'TH2')
wrf_lats, wrf_lons = latlon_coords(theta_2m)
wrf_lons = to_np(wrf_lons)
wrf_lats = to_np(wrf_lats)
    
# Timestamp
timestamp = to_np(theta_2m.Time).astype('M8[s]').astype('O').isoformat()
time = theta_2m.Time
time_str = str(time.values)
    
# Get cartopy projection from data set    
cart_proj = get_cartopy(theta_2m)

# Plot the relevant data
fig = plt.figure(figsize=(12,6))
ax = plt.axes(projection=cart_proj)
plt.contour(wrf_lons, wrf_lats, theta_2m, colors='black', transform=ccrs.PlateCarree())
plt.contourf(wrf_lons, wrf_lats, theta_2m, transform=ccrs.PlateCarree(), cmap=get_cmap('coolwarm'))
                 
plot_background(ax)

plt.colorbar(ax=ax, shrink=.98)

ax.set_extent([-104.35, -94.45, 36.37, 44.78])
ax.set_title('2m Potential Temperature (K) ' + time_str[:19])
                 
plt.show()

Solution

  • In plt.contour you can set the interval of contour lines with levels parameter:

    max_level = 2
    min_level = -2
    step_level = 0.5
    
    ax.contour(xx, yy, zz, colors = 'black', levels = np.arange(min_level, max_level + step_level, step_level))
    

    Complete Code

    import numpy as np
    import matplotlib.pyplot as plt
    
    N = 100
    
    x = np.linspace(0, 10, N)
    y = np.linspace(0, 10, N)
    xx, yy = np.meshgrid(x, y)
    
    zz = np.sin(xx) + np.sin(yy)
    
    
    max_level = 2
    min_level = -2
    step_level = 0.5
    
    fig, ax = plt.subplots(figsize = (6, 6))
    
    ax.contour(xx, yy, zz, colors = 'black', levels = np.arange(min_level, max_level + step_level, step_level))
    ax.contourf(xx, yy, zz, levels = np.arange(min_level, max_level + step_level, step_level))
    
    plt.show()
    
    • step_level = 0.5

      enter image description here

    • step_level = 0.1

      enter image description here