Skip to main content
 首页 » 编程设计

python之使用 numpy meshgrid 绘制二维等高线图的最佳方法

2024年11月24日13落叶无声

我正在寻找使用 numpy 网格创建等高线图的最佳方法。

我在列中的 excel 数据简单地看起来像这样:

x data values: -3, -2, -1, 0, 1, 2 ,3, -3, -2, -1, 0, 1, 2, 3 
y data values:  1,  1,  1, 1, 1, 1, 1,  2,  2,  2, 2, 2, 2, 2 
z data values:  7 , 5,  6, 5, 1, 0, 9,  5,  3,  8, 3, 1, 0, 4 

x 和 y 值定义了一个二维平面,其中长度(x 轴)为 7 个值,深度(y 轴)为 2 个值。 z 值定义相应点(或多或少是 z 轴)的颜色。

我试过:

import matplotlib.pyplot as plt 
import numpy as np 
 
x = [-3,-2,-1,0,1,2,3] 
 
y = [1,2] 
 
z = [7,5,6,5,1,0,9,5,3,8,3,1,0,4] 
 
x, y = np.meshgrid(x, y) 
 
A = np.array(z) 
B = np.reshape(A, (-1, 2)) 
 
fig = plt.figure() 
ax1 = plt.contourf(x, y, B) 
 
plt.show() 

我很确定我不了解 meshgrid 的工作原理。我是否必须使用整个 x 和 y 值列表才能工作?

如何创建长度 (x) 为 7、深度 (y) 为 2 且 z 值定义 x 和 y 值处的阴影/颜色的矩形 2d 图?

提前谢谢大家!

请您参考如下方法:

尝试

x_, y_ = np.meshgrid(x, y) 
z_grid = np.array(z).reshape(2,7) 
fig = plt.figure() 
ax1 = plt.contourf(x_,y_,z_grid) 
plt.show() 

编辑:如果你想平滑,根据你的评论,你可以尝试类似 scipy.ndimage.zoom() 的方法,如 here 所述。 ,即,在你的情况下

from scipy import ndimage 
 
z_grid = np.array(z).reshape(2,7) 
z_grid_interp = ndimage.zoom(z_grid, 100) 
x_, y_ = np.meshgrid(np.linspace(-3,3,z_grid_interp.shape[1]),np.linspace(1,2,z_grid_interp.shape[0])) 

然后像以前一样绘制:

fig = plt.figure() 
ax1 = plt.contourf(x_,y_,z_grid_interp) 
plt.show()