Matplotlib colorbar - 更改了限制的行为

问题描述 投票:3回答:2

我尝试使用matplotlib限制颜色条的范围。旧的行为是,可以使用绘图函数的vminvmax关键字来缩放颜色条。这会影响颜色本身和颜色条的标签。

现在的行为似乎是,只有颜色被缩放,而标签仍然是自动的。

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。

如何恢复保持行为并缩放颜色条的标签。

max_value = 100

max_value = 25

python matplotlib colorbar
2个回答
0
投票

问题是z中的值大于25.如果要将比例值限制为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)

Contour plot with truncated z values

或者,您可以通过将它们设置为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)

Contour plot with z values > 25 removed


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()

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.