python - matplotlib 中的极地等高线图 - 最好的(现代)方法?

标签 python numpy matplotlib

更新:我已经在我的博客 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 的。我做错了吗?

此外,将从模型返回的值放入列表然后对其进行重新整形似乎相当笨拙。有没有更好的方法来做到这一点?

最佳答案

您应该能够像往常一样将 ax.contourax.contourf 用于极坐标图...您的代码中有一些错误, 尽管。您将事物转换为弧度,然后在绘图时使用以度为单位的值。此外,当它需要 theta, r 时,您将 r, theta 传递给轮廓。

举个简单的例子:

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

enter image description here

关于python - matplotlib 中的极地等高线图 - 最好的(现代)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9071084/

相关文章:

python - 在 Python/matplotlib 中使用 xaxis_date() 手动设置 xticks

python - 替换一系列 Pandas 中的值

python - pyInstaller 可执行文件在 Ubuntu 12.04 Precise 上缺少模块 "_struct"

python - 拆分数组时减少内存使用的最佳实践

python-3.x - 试图 reshape 我的 numpy 数组以获得额外的维度

python - 如何使用 fmin_ncg 计算成本和 theta

python-tk 有未满足的依赖关系

python - 是否有更多 "Pythonic"的方式来组合 CSV 元素?

python - 为什么没有打印任何行并且估计系数为 NaN?

python - 我有数据 x,y,可以绘制散点图。如何在 python 中使用 matplot 更改频率标记?