Python 在等高线图的颜色条上设置限制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21952100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:56:41  来源:igfitidea点击:

Setting the limits on a colorbar of a contour plot

pythonmatplotlibcolorbar

提问by Jacques MALAPRADE

I have seen so many examples that just don't apply to my case. What I would like to do is set a simple minimum and maximum value for a colorbar. Setting a range for an image cmap is easy but this does not apply the same range to the minimum and maximum values of the colorbar. The code below may explain:

我已经看到了很多不适用于我的案例的例子。我想做的是为颜色条设置一个简单的最小值和最大值。为图像 cmap 设置范围很容易,但这不会将相同的范围应用于颜色条的最小值和最大值。下面的代码可以解释:

triang = Triangulation(x,y)
plt.tricontourf(triang, z, vmax=1., vmin=0.)
plt.colorbar()

The colorbar is still fixed to the limits of the data z, although the cmap range is now fixed between 0 and 1.

尽管 cmap 范围现在固定在 0 和 1 之间,但颜色条仍固定在数据 z 的范围内。

采纳答案by kiriloff

I propose you incorporate you plot in a figand get inspiration from this sample using the colorbar

我建议您将绘图合并到一个无花果中,并使用颜色条从这个示例中获得灵感

data = np.tile(np.arange(4), 2)
fig = plt.figure()
ax = fig.add_subplot(121)
cax = fig.add_subplot(122)
cmap = colors.ListedColormap(['b','g','y','r'])
bounds=[0,1,2,3,4]
norm = colors.BoundaryNorm(bounds, cmap.N)
im=ax.imshow(data[None], aspect='auto',cmap=cmap, norm=norm)
cbar = fig.colorbar(im, cax=cax, cmap=cmap, norm=norm, boundaries=bounds, 
     ticks=[0.5,1.5,2.5,3.5],)
plt.show()

you see that you can set boundsfor the colors in colorbar and ticks.

你看到你可以设置bounds颜色条和刻度中的颜色。

it is not rigourously what you want to achieve, but the hint to fig could help.

这不是您想要达到的严格要求,但 fig 的提示可能会有所帮助。

This other one uses ticksas well to define the scale of colorbar.

另一个ticks也用于定义颜色条的比例。

import numpy as np
import matplotlib.pyplot as plt

xi = np.array([0., 0.5, 1.0])
yi = np.array([0., 0.5, 1.0])
zi = np.array([[0., 1.0, 2.0],
               [0., 1.0, 2.0],
               [-0.1, 1.0, 2.0]])

v = np.linspace(-.1, 2.0, 15, endpoint=True)
plt.contour(xi, yi, zi, v, linewidths=0.5, colors='k')
plt.contourf(xi, yi, zi, v, cmap=plt.cm.jet)
x = plt.colorbar(ticks=v)
print x
plt.show()

回答by nedlrichards

I ran into the same problem, and came up with a concrete (albeit meaningless) example of this problem. The commented contourf command will create a color bar that has the same bounds as the data, and not the color limits.

我遇到了同样的问题,并提出了这个问题的具体(尽管毫无意义)示例。注释的 contourf 命令将创建一个与数据具有相同边界的颜色条,而不是颜色限制。

The level option of tricontourf seems to be a good way to work around this, though it requires the extend='both' option to include values that exceed the levels in the plot.

tricontourf 的 level 选项似乎是解决此问题的好方法,尽管它需要 extend='both' 选项以包含超出图中级别的值。

import matplotlib.tri as mtri
import numpy as np
from numpy.random import randn
from matplotlib import colors

numpy.random.seed(0)
x = randn(300)
y = randn(300)
z = randn(*x.shape)
triangles = mtri.Triangulation(x, y)
bounds=np.linspace(-1,1,10)
# sc = plt.tricontourf(triangles, z, vmax=1., vmin=-1.)
sc = plt.tricontourf(triangles, z, vmax=1., vmin=-1., levels = bounds,\
                    extend = 'both')
cb = colorbar(sc)
_ = ylim(-2,2)
_ = xlim(-2,2)

回答by farenorth

I thought this question pointed out a bug, but it turns it's a usage/compatability constraint. The solution is to create the contours for the range of the colorbar that you want, and use the extendkwarg. For more information, take a look at this issue. Thanks to @tcaswellfor providing this solution:

我认为这个问题指出了一个错误,但它变成了一个使用/兼容性约束。解决方案是为您想要的extend颜色条范围创建轮廓,并使用kwarg。有关更多信息,请查看此问题。感谢@tcaswell提供此解决方案:

import matplotlib.pyplot as plt
import numpy as np

x, y = np.mgrid[0:1:0.01, 0:1:0.01]
r = np.sqrt(x ** 2 + y ** 2)
z = np.sin(6 * np.pi * r)

fig0, ax0 = plt.subplots(1, 1, )
cf0 = ax0.contourf(x, y, z, np.arange(0, .5, .01),
                   extend='both')
cbar0 = plt.colorbar(cf0,)

enter image description here

在此处输入图片说明

From here if you don't like the colorbar ticks, you can adjust them with cbar0.set_ticks. I've verified that this also works with tricontourf.

从这里如果您不喜欢颜色条刻度,可以使用cbar0.set_ticks. 我已经验证这也适用于tricontourf.

I've simplified @tcaswell's code to that which is needed to get the desired result. Also, he used the new viridis colormap, but hopefully you get the idea.

我已将@tcaswell 的代码简化为获得所需结果所需的代码。此外,他使用了新的 viridis 颜色图,但希望您能理解。

回答by Yogesh Luthra

This is the simplest method probably.

这大概是最简单的方法了。

...(your code as shown)

...(您的代码如图所示)

plt.colorbar(boundaries=np.linspace(0,1,5)) 

...

...

回答by Daniel Marchand

Here is my own take, which I personally find to be a bit more clear and unified

这是我自己的看法,我个人认为它更清晰和统一

density=10
x = np.linspace(-1,1,num=density,endpoint=True)
y = np.linspace(-1,1,num=density,endpoint=True)
x = x.repeat(density)
y = np.hstack((y,)*density)
z = np.e**(-(x**2+y**2))

fig,  ax = plt.subplots()


vmin=0.30
vmax=0.60
plot_val = np.linspace(vmin, vmax, 300, endpoint=True)


cntr = ax.tricontourf(x, y, z, plot_val,
                      vmin=vmin,vmax=vmax,
                      extend='both'
                 )

cbar = fig.colorbar(cntr,ax=ax)
cbar.set_ticks(np.arange(0,0.61,0.1))