26

当用颜色填充网格时,例如在 pyplot 中使用 contourf 时,我需要找到一种方法来更改 pyplot 用来填充超出颜色栏指定范围的数据的颜色。我希望有一个静态颜色条,它不会自动更改其范围以适应数据的最大值/最小值,因此偶尔会有超出其界限的极端值是不可避免的,并且需要为这些值指定颜色。

超出颜色条边界的值的默认颜色是白色,如果颜色图没有白色作为其结束颜色,它可能会与周围的数据发生明显的冲突。示例图像如下所示 - 请注意当值超出颜色栏的负范围时白色填充:

在此处输入图像描述

我相信有一种方法可以指定在使用 rcParams 超出边界时使用哪种颜色,但我无法在任何地方找到有关此的信息。

任何帮助,将不胜感激。

4

1 回答 1

35

The out-of-bounds colors can be set using the set_over and set_under methods of the colormap; see the documentation. You'll need to specify these values when you create your colormap. I don't see any matplotlibrc setting to set the default for this, though. You might also want to ask on the matplotlib mailing list.

Edit: I see what is going on. The white area you describe is not beyond the limits of the color range. It is simply the blank background of the axes. Because you are only plotting certain levels, any levels outside that range will not be plotted at all, leaving those areas blank. To get what you want, do this:

cs = pyplot.contourf(x,y,z,levels=np.arange(50, 220, 20), cmap=pyplot.cm.jet, extend="both")
cs.cmap.set_under('k')
cs.set_clim(50, 210)
cb = pyplot.colorbar(cs)

The "extend" argument is the key; it tells contourf to go ahead and plot all contours, but collapse all outside the given range into "too big" and "too small" categories. The cs.set_clim call is necessary to work around an oddity I discovered in contourf while debugging this; for some reason when you use extend, it manipulates the data limits, so we need to reset them back to what we want them to be.

Also, just as a matter of style, you shouldn't be doing things like Colormap.set_under(cmap,color='k'). This is calling the class method and explicitly passing the instance in, which is an odd way to do it. Just do cmap.set_under(color="k").

于 2012-07-08T19:59:37.470 回答