Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyPlot ColorMesh creates plot with wrong color mapping

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?

like image 356
aryndin Avatar asked Feb 02 '26 22:02

aryndin


1 Answers

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

like image 115
ImportanceOfBeingErnest Avatar answered Feb 05 '26 11:02

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!