I want to make contour plots with colorbars that are symmetric about zero and have ticks at the maximum and minimum values. I am having a problem where the end ticks on my colorbars are not showing.
Here is an example:
fig, ax = plt.subplots()
A = np.random.random((10,10))*10-5
x = np.arange(0, A.shape[1])
y = np.arange(0, A.shape[0])
minval=-5
maxval=5
im1 = ax.contourf(x,y,A,150, vmin=minval, vmax=maxval,cmap="BrBG",extend='both')
cbar = ax.figure.colorbar(
im1,
ax=ax,
ticks=[minval, minval/2, 0, maxval/2, maxval],
orientation="vertical",
)
Which results in this figure (it will not let me embed the image, see link), that has tick marks at 0 and +/-2.5 but not +/-5:
contour plot with a colorbar that has ticks at -2.5, 0 and 2.5 but not at -5 or 5
I tried these following add-ons with no avail:
im1.set_clim(minval, maxval)
cbar.ax.set_xticklabels([minval, minval/2, '0', maxval/2, maxval])
plt.show()
I'm nearly positive that this used to work fine but has recently been skipping out on the end tick marks. I'm running it in a jupyter notebook. Ideas?
If you call contourf(..., levels=150, ...)
, matplotlib will create 151 equally spaced boundaries between the minimum and maximum of the data. The way np.random.random
works, the minimum of A
is slightly larger than -5
and the maximum slightly smaller than 5
. So, these extreme values don't belong to the level boundaries. And won't be visible in the colorbar. To have them visible, the level boundaries could be set explicitly to include these values:
from matplotlib import pyplot as plt
import numpy as np
fig, ax = plt.subplots()
A = np.random.random((10, 10)) * 10 - 5
x = np.arange(0, A.shape[1])
y = np.arange(0, A.shape[0])
minval = -5
maxval = 5
im1 = ax.contourf(x, y, A, levels=np.linspace(minval, maxval, 151), cmap="BrBG", extend='both')
cbar = fig.colorbar(
im1,
ax=ax,
ticks=[minval, minval/2, 0, maxval/2, maxval],
orientation="vertical"
)
cbar.ax.set_yticklabels([minval, minval/2, "0", maxval/2, maxval])
plt.show()
Also note that for a vertical colorbar, the y
-direction is used (cbar.ax.set_yticklabels
).