Search code examples
pythonmatplotlibcolorbarcartopy

Is there a way to make the colorbar show only a range of values using matplotlib?


I am plotting a map of sea surface salinity and I want to show only salinity values above a certain threshold (26). I changed the colormap properly so it shows it using the function

vmin = 26

The colormap is fine but the colormap is still showing values less than 26... is there a similar function like vmin for the colorbar?

this is my plot:

fig = plt.figure(figsize=(15,5))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent([-90, 8, 5, 85], crs=ccrs.PlateCarree())
x = ax.contourf(sss_md.longitude,sss_md_tm.latitude,sss_md_tm, 100,cmap='jet', vmin=26)
ax.coastlines()
#ax.add_feature(cfeature.LAND, zorder=100, edgecolor='k')
gridlines = ax.gridlines(draw_labels=True)
cbar = plt.colorbar(x, fraction=.046, pad=0.04)
cbar.set_label('SSS', labelpad=15, y=.5, rotation=270)
ax.text(.5,-.12, 'Longitude' , va='bottom' , ha='center', rotation='horizontal', rotation_mode= 'anchor',transform=ax.transAxes)
ax.text(-.1, .5, 'Latitude' , va='bottom' , ha='center', rotation='vertical', rotation_mode= 'anchor',transform=ax.transAxes)
plt.title('SSS')
plt.show()

my map

Notice how the color bar still shows 4.8 - 37.2, but I want it to only include 26 - 37.2 (or higher).

I tried putting vmin in:

cbar = plt.colorbar(x, vmin=26, fraction=.046, pad=0.04)

but it didn't recognize vmin and thus did not work.


Solution

  • Correct answer from users above:

    np.linspace(26,40,50) or say np.arange(26,40,0.5) instead of np.arange(26,40,50)