I have a plot that I artificially saturate and would like the colorbar to reflect this. My current code saturates the image fine, but the colorbar still shows the saturated values. I would like the colorbar to stop at the maximum value that is still plotted, maybe indicated by an arrow (I have seen the 'extend' keyword for this but haven't been able to apply it).
This is what I have so far:
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-1,1,1000)
x,y = np.meshgrid(x,x)
z = np.exp(-(x**2+y**2))
plt.contourf(x,y,z,100,vmax=.75*np.max(z))
plt.colorbar()
plt.show()
What can I do to
You are plotting a contour plot. This means you get the colors of the levels in the colorbar. The extend
keyword to colorbar does not make much sense for such plot, since there are no colors outside of any range to be shown.
You may of course set the levels, such that the last level comprises of "the rest of the range". Then you may use the extend
keyword for contourf
.
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-1,1,1000)
x,y = np.meshgrid(x,x)
z = np.exp(-(x**2+y**2))
levels = np.linspace(z.min(),0.75*z.max(),100)
levels[-1] = z.max()
plt.contourf(x,y,z,levels, extend="both", vmax=0.75*z.max())
plt.colorbar()
plt.show()
It seems in this case a more reasonable way to plot the data (which is dense enough anyways) is to use a pcolormesh
plot.
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-1,1,1000)
x,y = np.meshgrid(x,x)
z = np.exp(-(x**2+y**2))
plt.pcolormesh(x,y,z, vmax=0.75*z.max())
plt.colorbar(extend="both")
plt.show()