colormap, always centered on zero

I am trying to plot a matrix with positive and negative numbers. The numbers will be in an interval from -1 to 1 but not at the complete range. Numbers could sometimes be in the range from -0.2 to +0.8 for example (See code below). I want to use the bwr-colormap (blue -> white - red) such that zero is always color-coded in white. -1 should be colorcoded in the darkest possible blue and +1 should be colorcoded in the darkest possible red. Here comes an example, where both plots are only distinguishable by their colorbar.

import numpy
from matplotlib import pyplot as plt

# some arbitrary data to plot
x = numpy.linspace(0, 2*numpy.pi, 30)
y = numpy.linspace(0, 2*numpy.pi, 20)
[X, Y] = numpy.meshgrid(x, y)
Z = numpy.sin(X)*numpy.cos(Y)

fig = plt.figure()
plt.ion()
plt.set_cmap('bwr') # a good start: blue to white to red colormap

# a plot ranging from -1 to 1, hence the value 0 (the average) is colorcoded in white
ax = fig.add_subplot(1, 2, 1)
plt.pcolor(X, Y, Z)
plt.colorbar()

# a plot ranging from -0.2 to 0.8 hence 0.3 (the average) is colorcoded in white
ax = fig.add_subplot(1, 2, 2)
plt.pcolor(X, Y, Z*0.5 + 0.3)   # rescaled Z-Data
plt.colorbar()

The figure created by this code can be seen here: 用发布的代码创建图

As stated above, i am looking for a way to always color-code the values with the same colors, where -1: dark blue, 0: white, +1: dark red. Is this a one-liner and i am missing something or do i have to write something myself for this?

EDIT: After digging a little bit longer i found a satisfying answer myself, not touching the colormap but rather using optional inputs to pcolor (see below). Still, I will not delete the question as i could not find an answer on SO until i posted this question and clicked on the related questions/answers. On the other hand, i wouldn't mind if it got deleted, as answers to exactly this question can be found elsewhere if one is looking for the right keywords.


Apparently, I found the answer myself after digging a little longer. pcolor offers the optional input vmin and vmax . If I set them to -1 and 1 respectively, it exactly solves the problem. The colorcoding then seems to be relative to vmin and vmax, not to the min and max of the data, which is plotted. So changing the plot command (and comments) to

# a plot ranging from -1 to 1, where the value 0 is colorcoded in white
ax = fig.add_subplot(1, 2, 1)
plt.pcolor(X, Y, Z, vmin=-1, vmax=1) # vmin, vmax not needed here
plt.colorbar()

# a plot ranging from -0.2 to 0.8, where the value 0 is colorcoded in white
ax = fig.add_subplot(1, 2, 2)
plt.pcolor(X, Y, Z*0.5 + 0.3, vmin=-1, vmax=1)   # rescaled Z-Data
plt.colorbar()

It produces a figure as I need it: 正确的数字

So, setting vmin=-1, vmax=1 does the job, i do not have to change stuff on the colormap itself.

链接地址: http://www.djcxy.com/p/22474.html

上一篇: “不完整的文件块”是什么意思?

下一篇: 色彩贴图始终以零为中心