Matplotlib中的极地等高线图

9
我有一组数据,想使用Matplotlib在极坐标下生成等高线图。
我的数据如下:
- `theta` - 角度值的1D数组 - `radius` - 半径值的1D数组 - `value` - 我想用于等高线的值的1D数组
这些都是对齐的1D数组,例如:
theta   radius   value
30      1        2.9
30      2        5.3
35      5        9.2

也就是说,所有的值都重复了足够的次数,以便这三个变量的每一行定义一个点。

我该如何从这些值创建极坐标等高线图? 我考虑将半径和极角值转换为x和y值,并在笛卡尔坐标系中处理,但是contour函数似乎需要2D数组,我无法完全理解为什么。

有任何想法吗?

2个回答

9
Matplotlib的contour()函数期望数据被排列成一个二维点网格和每个网格对应的值。如果你的数据自然地排列成一个网格,你可以将r、theta转换为x、y,并使用contour(r*np.cos(theta), r*np.sin(theta), values)来制作图表。
如果您的数据不是自然网格,则应遵循Stephen的建议,并使用griddata()将您的数据插值到网格上。
以下脚本显示了两者的示例。
import pylab as plt
from matplotlib.mlab import griddata
import numpy as np

# data on a grid
r = np.linspace(0, 1, 100)
t = np.linspace(0, 2*np.pi, 100)
r, t = np.meshgrid(r, t)
z = (t-np.pi)**2 + 10*(r-0.5)**2

plt.subplot(121)
plt.contour(r*np.cos(t), r*np.sin(t), z)

# ungrid data, then re-grid it
r = r.flatten()
t = t.flatten()
x = r*np.cos(t)
y = r*np.sin(t)
z = z.flatten()
xgrid = np.linspace(x.min(), x.max(), 100)
ygrid = np.linspace(y.min(), y.max(), 100)
xgrid, ygrid = np.meshgrid(xgrid, ygrid)
zgrid = griddata(x,y,z, xgrid, ygrid)

plt.subplot(122)
plt.contour(xgrid, ygrid, zgrid)

plt.show()

enter image description here


非常感谢您清晰明了的回答。我已经发布了一个关于坐标轴的后续问题 - https://dev59.com/91_bs4cB2Jgan1zng9RS。不知道您是否能够帮忙解决? - robintw

3

我不确定是否可以直接进行极坐标等值线图,但如果您将其转换为笛卡尔坐标,您可以使用griddata函数将您的1D数组转换为2D。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接