开发者

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 u开发者_运维问答niform 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()


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.

Matplotlib - Contour plot with single value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜