Matplotlib - 单值等高线图
我想绘制一些数据的等值线图,但字段中的所有值可能都相同。这会导致 matplotlib 中出现错误,这是有道理的,因为实际上没有要创建的轮廓。例如,如果运行下面的代码,您将收到错误,但删除 zi
的第二个定义,它会按预期运行。
如果某些数据是均匀场,如何制作“等高线”图?我希望它看起来就像常规等高线图(有一个填充某种颜色的盒子并在侧面显示颜色条。颜色条可以是统一的颜色,或者仍然显示 15 种颜色的范围,我不知道不在乎)。
代码:
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()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,
contourf
完美地处理了它,令人窒息的是contour
。为什么不这样做:
这样,如果存在均匀场,您将得到一个填充的(默认为绿色)框,否则将得到一个带有线条的填充等值线图。
Well,
contourf
handles it perfectly, it'scontour
that chokes.Why not just do this:
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.