Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying colours when using matplotlib's pcolormesh

Using matplotlib, I want to be able to specify exact colors with pcolormesh. Here is what I have tried

import numpy as np
from matplotlib import pyplot as plt

imports at the top

X = np.linspace(0,1,100)
Y = np.linspace(0,1,100)
X,Y = np.meshgrid(X,Y)
Z = (X**2 + Y**2) < 1.
Z = Z.astype(int)
Z += (X**2 + Y**2) < .5

set up a bunch of fake data. Z is only 0s, 1s, and 2s (this is like my real problem).

plt.pcolormesh(X,Y,Z,color=[(1,1,0),(0,0,1),(1,0,1)])

call pcolormesh with a color argument in a vain attempt to get a yellow, blue, and magenta plot. In fact, I got the default colors!

pcolormesh

My question is: how do I call pcolormesh to get the first area to be yellow, the second blue, and the third magenta?

like image 379
luispedro Avatar asked Nov 08 '12 17:11

luispedro


People also ask

How do you change colors on Pcolormesh?

pcolormesh() examples To use a different number of colors, change the colormap with the cmap named argument. The number of colors in the colormap will determine the color resolution of the resulting images.

How does pcolormesh work?

The pcolormesh() function in pyplot module of matplotlib library is used to create a pseudocolor plot with a non-regular rectangular grid. Parameters: This method accept the following parameters that are described below: C : This parameter contains the values in 2D array which are to be color-mapped.


1 Answers

One way is to use a custom colormap:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import colors as c

X = np.linspace(0,1,100)
Y = np.linspace(0,1,100)
X,Y = np.meshgrid(X,Y)
Z = (X**2 + Y**2) < 1.
Z = Z.astype(int)
Z += (X**2 + Y**2) < .5

cMap = c.ListedColormap(['y','b','m'])

plt.pcolormesh(X,Y,Z,cmap=cMap)
plt.show()

plot showing custom color map with yellow, blue, magenta

like image 82
Keith Avatar answered Oct 14 '22 10:10

Keith