在matplotlib中绘制极地等高线图-最佳(现代)方法是什么?

2024-09-28 22:29:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

而且,将从模型返回的值放入一个列表中,然后对其进行重新格式化,这看起来相当笨拙。有更好的办法吗?


Tags: 方法代码comhttpformatplotlibnp绘制
2条回答

x、y的形状和值必须相同。您的数据形状是:

>>> x.shape, y.shape, values.shape
((36, 7), (36, 7), (7, 36))

所以把轮廓(x,y,值)改为轮廓(x,y,值.T)。

你应该可以像平常一样用ax.contourax.contourf绘制极坐标图。。。不过,您的代码中有一些bug。可以将事物转换为弧度,但在绘图时使用以度为单位的值。另外,您传入r, theta以确定它期望的theta, r时间。

举个简单的例子:

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

相关问题 更多 >