我尝试使用matplotlib限制颜色条的范围。以前的行为是,可以使用绘图功能的vmin
和vmax
关键字来缩放颜色条。这会影响颜色本身和颜色条的标签。
现在的行为似乎是,只对颜色进行了缩放,而标签仍然是自动标签。
import numpy
import numpy.random
import matplotlib.pyplot as plt
# create somehing to plot, maximum value should be much large than 10
z = numpy.random.rand(20, 20) * 57.8412
t = numpy.linspace(0, 1, 20)
x, y = numpy.meshgrid(t, t)
# this is supposed to be the maximum value of the plot
max_value = 25 # or 100
fig = plt.figure()
axis = fig.add_subplot(1, 1, 1)
plot = axis.contourf(x, y, z, 100, cmap=None, vmin=0, vmax=max_value)
cbar = plt.colorbar(plot)
plt.show(block=False)
两张图片的颜色条标签保持相同(最多58张),即使第一张图片的最大值应为25,第二张图片的最大值为100。
如何还原保持行为并缩放颜色栏的标签。
答案 0 :(得分:0)
问题是z中的值大于25。如果要将比例值限制为25或更小,则需要截断z中的值大于25,或者在将z值大于25之前将其删除。情节。
以下是将z中的值截断为25或更小的示例:
import numpy
import numpy.random
import matplotlib.pyplot as plt
znew = z
znew[z > 25] = 25
t = numpy.linspace(0, 1, 20)
x, y = numpy.meshgrid(t, t)
# this is supposed to be the maximum value of the plot
max_value = 25 # or 100
fig = plt.figure()
axis = fig.add_subplot(1, 1, 1)
plot = axis.contourf(x, y, znew, 100, cmap=None, vmin=0, vmax=max_value)
cbar = plt.colorbar(plot)
plt.show(block=False)
或者,您可以通过将它们设置为NaN
来删除这些值:
znew = z
znew[z > 25] = numpy.nan
t = numpy.linspace(0, 1, 20)
x, y = numpy.meshgrid(t, t)
# this is supposed to be the maximum value of the plot
max_value = 25 # or 100
fig = plt.figure()
axis = fig.add_subplot(1, 1, 1)
plot = axis.contourf(x, y, znew, 100, cmap=None, vmin=0, vmax=max_value)
cbar = plt.colorbar(plot)
plt.show(block=False)
答案 1 :(得分:0)
我不确定我是否了解所需的结果,但我认为您希望明确设置水平。
import numpy as np
import matplotlib.pyplot as plt
# create somehing to plot, maximum value should be much large than 10
z = np.random.rand(20, 20) * 57.8412
t = np.linspace(0, 1, 20)
x, y = np.meshgrid(t, t)
# this is supposed to be the maximum value of the plot
max_value = 25 # or 100
fig, ax = plt.subplots()
ax.set_title(f"max_value={max_value}")
cntr = ax.contourf(x, y, z, levels=np.arange(max_value+1), vmin=0, vmax=max_value)
cbar = fig.colorbar(cntr)
plt.show()