3

I try to create a Color Mesh plot using a map of xy-coordinates and colors in this way:

from matplotlib.colors import ListedColormap
import numpy as np
%pylab inline

colors = ListedColormap(['red', 'blue', 'yellow'])
xx,yy = np.meshgrid(np.arange(1, 6, 1), np.arange(1, 6, 1))
zz = np.array([[1,1,1,1,1],
               [1,1,1,1,1],
               [1,1,1,1,1],
               [2,2,0,0,0],
               [2,2,0,0,0]])
pyplot.pcolormesh(xx, yy, zz, cmap = colors)

It works ok when there is a list of three colors and I try to map xy-points into all of that colors (like in the code above):

enter image description here

But when there is a list of three colors, and I try to map points only into two of them, mapping goes wrong:

zz = np.array([[1,1,1,1,1],
               [1,1,1,1,1],
               [1,1,1,1,1],
               [0,0,0,0,0],
               [0,0,0,0,0]])
pyplot.pcolormesh(xx, yy, zz, cmap = colors)

enter image description here

It should map into colors 0 (red) and 1 (blue), but I get plot with 0 (red) and 2 (yellow) colors. Where is the mistake?

1 Answer 1

5

Colormaps are normalized between 0 and 1. When they are used in a plot, the normalization is transfered to the minimum and maximum value of the data. If 0 and 1 are minimum and maximum, 0 will be the first color of the map (red) and 1 will the last (yellow).

What you need is a normalization which takes the desired colormap behaviour into account. The easiest option is to use vmin and vmax

zz = np.array([[1,1,1,1,1],
               [1,1,1,1,1],
               [1,1,1,1,1],
               [0,0,0,0,0],
               [0,0,0,0,0]])
plt.pcolormesh(xx, yy, zz, cmap = colors, vmin=0,vmax=colors.N)

enter image description here

1
  • Thank you very much, you've made my day!
    – aryndin
    Commented Oct 8, 2017 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.