Skip to content Skip to sidebar Skip to footer

Matplotlib Contourf With 3 Colors

I would like to make a contour plot with 3 distinct colors. So far, my code looks like the following: import numpy as np import matplotlib.pyplot as plt xMin = 0 xMax = 3 xList =

Solution 1:

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 ListedColormap.

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')

enter image description here


Post a Comment for "Matplotlib Contourf With 3 Colors"