用Python从已知值绘制三维曲面

2024-09-29 01:38:45 发布

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

我有一组大约2000个文件,看起来像:10_20.txt10_21.txt10_21.txt。。。,10_50.txt。。。,11.20.txt。。。,11.50.txt。。。,20_50.txt

文件名中的第一个值,我们将称为x,从10到20的步骤为1,而文件名中的第二个值,我们将称为y,从20到50,以1为步进。在

在这些文件中,有一堆值和另一个我要提取的值,我们称之为z。在

{10>循环从CDI文件中提取一个文件并添加到列表中。在

我现在的问题是,如果我有2个numpy数组,它们看起来像:

x = np.arange(10,20,1) y = np.arange(20,50,1)

如果一个z列表中有~2000floats,那么绘制z如何依赖x和{}的最佳方法是什么?有标准的方法吗?在

我一直在想最好是从文件中提取xy和{},然后将它们添加到多维数组中。如果是这样的话,谁能告诉我如何从文件名中提取xy值的正确方向。在


Tags: 文件方法numpytxt列表标准文件名np
2条回答

假设您有一个ready函数,比如read_z_from_file(filename),它返回文件中包含的z-值,可以这样做:

import numpy as np

x = np.arange(10,20,1, dtype = np.int)
y = np.arange(20,50,1, dtype = np.int)
z = np.zeros((x.shape[0],y.shape[0]))

for i,x0 in enum(x):
   for j,y0 in enum(y):
      filename = '{}_{}.txt'.format(x0,y0)
      z[i,j] = read_z_from_file(filename)

然后您可以用imshowmatplotlib来可视化z。例如:

^{pr2}$

编辑

为了回答OP的问题,有多种方法可以可视化您的数据。imshowmatshow两者都有相同的功能,但显示细节不同。此外,您还可以生成等高线图或三维曲面。这在很大程度上取决于你想看什么。不管怎样,假设上面的代码能满足您的需要,我在下面展示一些使用四种不同方法来显示相同示例数据的代码。您可以在内置的help()函数以及matplotlibnumpy文档页面中找到关于这些不同方法的更多信息。在

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D ##for the 3d surface plot
from matplotlib import cm

#non-integer spacing of the coordinates
x = np.linspace (10, 20, 15)
y = np.linspace (20, 50, 70)

#gridding the coordinates
xm, ym = np.meshgrid(x,y)

#example data
z = np.exp(-( 0.1*(xm-12)**2 + 0.05*(ym-40)**2 ) )

#opening a figure
fig = plt.figure(figsize=(6,6))

#matshow:
ax1 = fig.add_subplot(221)
res = ax1.matshow(
    z,
    origin = 'lower',
    aspect = 'auto',
    extent=[x[0],x[-1],y[0],y[-1]],
    )
fig.colorbar(res)
ax1.set_title('matshow', y=1.1)

#imshow
ax2 = fig.add_subplot(222)
res = ax2.imshow(
    z,
    origin = 'lower',
    aspect = 'auto',
    extent=[x[0],x[-1],y[0],y[-1]],
    )
fig.colorbar(res)
ax2.set_title('imshow')


#contourf
ax3 = fig.add_subplot(223)
res = ax3.contourf(xm,ym,z)
fig.colorbar(res)
ax3.set_title('contourf')

#3d surface
ax4 = fig.add_subplot(224, projection='3d')
res = ax4.plot_surface(
    xm,ym,z,
    cmap = cm.viridis,
    antialiased=False
)
fig.colorbar(res, pad = 0.1)
ax4.set_title('3d surface')

fig.tight_layout()
plt.show()

最后的情节如下:

the result of the above given code

使用x和y作为坐标,并为能量z设置一个点

一个表格也可以,因为你还没有说明x和y几何图形除了作为标签外还有其他的数值用途。在

相关问题 更多 >