Matplotlib中的极轴等高线图

2024-04-18 23:24:16 发布

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

我有一组数据,我想使用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值,并在笛卡尔坐标系下进行,但是轮廓函数似乎需要二维数组,我不太明白为什么。

有什么想法吗?


Tags: 数据定义matplotlibvalue半径数组次数角度
2条回答

我不知道是否可以直接绘制极坐标,但如果转换为笛卡尔坐标,可以使用^{}函数将1D数组转换为2D

Matplotlib的contour()函数期望将数据排列为点的二维网格和这些网格点的相应值网格。如果数据自然地排列在网格中,则可以将r、theta转换为x、y,并使用contour(r*np.cos(theta), r*np.sin(theta), values)绘制图。

如果您的数据不是自然网格化的,那么您应该遵循史蒂芬的建议,并使用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

相关问题 更多 >