当我添加任意值时,matplotlib (Python) 颜色条中的刻度线定位不正确
Ticks in colorbar of matplotlib (Python) are not positioned correctly when I add an arbitrary value
我已经绘制了一个 contourf(和 contour to plot lines on top)图,带有颜色条和等距数据级别,没问题。但是,当我添加任意级别值(示例中的1.1
)时,它在颜色条中的表示不正确。
在下面的可重现示例中,除了步长为 0.5
的水平之外,还添加了一个步长为 0.1
的新值。在颜色条中,距离是相同的。
我该如何纠正?
提前致谢
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()
您应该将 spacing
参数传递给 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')
我已经绘制了一个 contourf(和 contour to plot lines on top)图,带有颜色条和等距数据级别,没问题。但是,当我添加任意级别值(示例中的1.1
)时,它在颜色条中的表示不正确。
在下面的可重现示例中,除了步长为 0.5
的水平之外,还添加了一个步长为 0.1
的新值。在颜色条中,距离是相同的。
我该如何纠正?
提前致谢
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()
您应该将 spacing
参数传递给 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')