Matplotlib - Contour plot with single value

筅森魡賤 提交于 2021-01-27 05:59:10

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/5572500/matplotlib-contour-plot-with-single-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!