Matplotlib bwr-colormap, always centered at zero

I am trying to build a matrix with positive and negative numbers. Numbers will range from -1 to 1, but not in the full range. For example, numbers can range from -0.2 to +0.8 (see Code below). I want to use bwr-colormap (blue β†’ white - red), so zero always has a color coding in white. -1 should be color coded in the darkest blue, and +1 should be color coded in dark red. Here is an example where both scenes are distinguishable only by their color panel.

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 image created by this code can be seen here: figure create with posted code

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

EDIT: After digging a little longer, I found a satisfactory answer myself, not touching the color map, but using additional inputs for pcolor (see below). However, I will not delete the question, since I could not find the answer to SO until I posted this question and clicked on the related questions / answers. On the other hand, I would not mind if it was deleted, as the answers to this question can be found elsewhere if you are looking for the right keywords.

+6
source share
1 answer

Apparently, I found the answer myself after digging a little longer. pcolor offers an additional input vmin and vmax . If I set them to -1 and 1 respectively, it definitely solves the problem. Then color coding refers to vmin and vmax, and not to min and max data that is plotted. Therefore, 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() 

He creates the shape that I need: correct figure

So, setting vmin=-1, vmax=1 performs the task, I do not need to change the material in the color map itself.

+3
source

Source: https://habr.com/ru/post/974348/


All Articles