I have plotted a contourf (and contour to plot lines on top) graph with colorbar and equispaced data levels and it is ok. However, when I add an arbitrary level value(1.1
in the example), it is not representd correctly in the colorbar.
In the reproducible example below, besides the levels with steps of 0.5
, a new value with a step of 0.1
is added. In the colorbar, the distances are the same.
How can I correct this?
Thanks in advance
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-2.0, 3.0, 0.025)
y = np.arange(-2.0, 3.0, 0.025)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
levels = np.arange(-2,3,1)
levels=np.append(levels,1.1)
levels=np.sort(levels)
fig, ax = plt.subplots()
c = plt.contourf(X, Y, Z, levels=levels,alpha=0.15)
cs = plt.contour(X, Y, Z, levels=levels)
ax.clabel(cs, inline=1, fontsize=10)
cbar=plt.colorbar(c)
plt.show()
You should pass spacing
parameter to plt.colorbar
:
spacing:
uniform
spacing gives each discrete color the same space;proportional
makes the space proportional to the data interval.
cbar=plt.colorbar(c, spacing = 'proportional')