Matplotlib contourf with 3 colors
<p>I would like to make a contour plot with 3 distinct colors. So far, my code looks like the following:</p>

<pre><code>import numpy as np
import matplotlib.pyplot as plt

xMin = 0
xMax = 3
xList = np.linspace(xMin, xMax, 10)
X1, X2 = np.meshgrid(xList, xList)
Z = []
# do some processing with Z
# Z now contains 0, 0.5 or 1, e.g. Z = [0, 0, 0, 1, 1, 0.5, 1, 0.5...]
Z = Z.reshape((len(X1), len(X2)))
plt.contourf(X1, X2, Z,alpha=0.5)
</code></pre>

<p>Now I'd like to plot every contour where Z = 0 as red, Z = 0.5 as green and Z = 1 as blue. I do not want to have smooth transitions between red/green/blue, but just a color switch.
I played around with the color and levels option, but it did not really work out as expected. </p>

<p>Is the contour plot the right way to go here?</p>

<p>You can control the colors of a contour plot with the colors option but you might want to use imshow to avoid interpolation between the levels. You create a colormap for imshow with discrete levels using <a href="http://matplotlib.org/api/colors_api.html#matplotlib.colors.ListedColormap" rel="nofollow">ListedColormap</a>.</p>

<pre><code>data = 0*np.ones((20,20))
data[5:15,5:15] = 0.5
data[7:12,8:16] = 1

# contourf plot
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.contourf(data, [0,0.4,0.9], colors = ['r','g','b']) 
ax1.set_aspect('equal')
ax1.set_title('contourf')

# imshow plot
ax2 = fig.add_subplot(2,2,2)
# define colr map
cmap = colors.ListedColormap(['r','g','b'])
bounds = [0, 0.4,0.6, 1.1]
norm = colors.BoundaryNorm(bounds, cmap.N)

ax2.imshow(data, interpolation = 'none', cmap=cmap, norm=norm)
ax2.set_title('imshow')
</code></pre>

<p><a href="http://i.stack.imgur.com/dqsww.png" rel="nofollow"><img src="http://i.stack.imgur.com/dqsww.png" alt="enter image description here"></a></p>

python matplotlib