Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib - Contour plot with single value

I want to make a contour plot of some data, but it is possible that all values in the field at the same value. This causes an error in matplotlib, which makes sense since there really isn't a contour to be created. For example, if you run the code below, you will get an error, but delete the second definition of zi and it runs as expected.

How can I make a "contour" plot for some data if it is a uniform field? I want it to look just like the regular contour plot (to have a box filled with some color and to show a color bar on the side. The color bar could be a uniform color, or still show a range of 15 colors, I don't care).

Code:

from numpy        import array
import matplotlib.pyplot as plt

xi = array([0., 0.5, 1.0])
yi = array([0., 0.5, 1.0])
zi = array([[0., 1.0, 2.0],
            [0., 1.0, 2.0],
            [0., 1.0, 2.0]])
zi = array([[1.0, 1.0, 1.0],
            [1.0, 1.0, 1.0],
            [1.0, 1.0, 1.0]])

CS = plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k')
CS = plt.contourf(xi, yi, zi, 15, cmap=plt.cm.jet)
plt.colorbar()
plt.show()
like image 936
Scott B Avatar asked Apr 06 '11 20:04

Scott B


1 Answers

Well, contourf handles it perfectly, it's contour that chokes.

Why not just do this:

import numpy as np
import matplotlib.pyplot as plt

xi = np.array([0., 0.5, 1.0])
yi = np.array([0., 0.5, 1.0])
zi = np.ones((3,3))

try:
    CS = plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k')
except ValueError:
    pass
CS = plt.contourf(xi, yi, zi, 15, cmap=plt.cm.jet)

plt.colorbar()
plt.show()

This way, you'll get a filled (green, by default) box if there's a uniform field, and a filled contour plot with lines otherwise.

enter image description here

like image 133
Joe Kington Avatar answered Oct 06 '22 07:10

Joe Kington