更新:我已经在我的博客http://blog.rtwilson.com/producing-polar-contour-plots-with-matplotlib/上写了一篇完整的文章介绍了我发现的方法--你可能想先去那里看看。
我正在尝试在matplotlib中绘制极等值线图。我在互联网上找到了各种各样的资源,(a)我似乎不能让我的代码工作,(b)许多资源看起来相当陈旧,我想知道现在是否有更好的方法。例如,http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg01953.html建议可能很快就会做一些事情来改善事情,那是在2006年!
我很希望能够绘制合适的极轮廓图-就像pcolor可以让你绘制它的类型的图(参见下面的注释部分),但我似乎找不到任何方法来做到这一点,所以我首先转换为笛卡尔坐标。
不管怎样,我有下面的代码:
from pylab import *
import numpy as np
azimuths = np.arange(0, 360, 10)
zeniths = np.arange(0, 70, 10)
values = []
for azimuth in azimuths:
for zenith in zeniths:
print "%i %i" % (azimuth, zenith)
# Run some sort of model and get some output
# We'll just use rand for this example
values.append(rand())
theta = np.radians(azimuths)
values = np.array(values)
values = values.reshape(len(zeniths), len(azimuths))
# This (from http://old.nabble.com/2D-polar-surface-plot-td28896848.html)
# works fine
##############
# Create a polar axes
# ax = subplot(111, projection='polar')
# pcolor plot onto it
# c = ax.pcolor(theta, zeniths, values)
# show()
r, t = np.meshgrid(zeniths, azimuths)
x = r*np.cos(t)
y = r*np.sin(t)
contour(x, y, values)
当我运行它的时候,我得到了一个错误TypeError: Inputs x and y must be 1D or 2D.
。我不确定为什么我会得到这个,因为x和y都是2D的。我做错了什么吗?
此外,将我的模型返回的值放到一个列表中,然后对其进行重塑,这似乎是相当笨拙的。有没有更好的方法来做这件事?
发布于 2012-02-01 00:21:00
您应该能够像往常一样使用极地图的ax.contour
或ax.contourf
...不过,您的代码中有一些bug。您可以将事物转换为弧度,但在打印时使用度数。此外,当contour需要theta, r
时,您会将r, theta
传递给contour。
举个简单的例子:
import numpy as np
import matplotlib.pyplot as plt
#-- Generate Data -----------------------------------------
# Using linspace so that the endpoint of 360 is included...
azimuths = np.radians(np.linspace(0, 360, 20))
zeniths = np.arange(0, 70, 10)
r, theta = np.meshgrid(zeniths, azimuths)
values = np.random.random((azimuths.size, zeniths.size))
#-- Plot... ------------------------------------------------
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
ax.contourf(theta, r, values)
plt.show()
发布于 2012-01-31 10:03:36
x、y和值的形状必须相同。您的数据形状为:
>>> x.shape, y.shape, values.shape
((36, 7), (36, 7), (7, 36))
因此,将轮廓(x,y,values)更改为轮廓(x,y,values.T)。
https://stackoverflow.com/questions/9071084
复制相似问题