从熊猫CSV文件绘制3D图

时间:2020-01-29 22:08:17

标签: python pandas matplotlib plot 3d

所以我有一个熊猫数据框,如下所示:

Time         Velocity       Cxx
-1.0         -10000         0.000
-0.999       -10000         0.010
-0.998       -10000         0.011
 ...         ...             ...
0.998       -10000         0.011
0.999       -10000         0.010
 1.0        -10000         0.000
 ...         ...             ...
 -1.0        -5000         0.000
-0.999       -5000         0.050
-0.998       -5000         0.055
 ...          ...           ...
0.998       -5000         0.055
0.999       -5000         0.050
 1.0        -5000         0.000

等等换句话说,“时间”列是从[-1,1]采样而速度是从[-10000,10000]采样。 Cxx值是我的函数在(时间,速度)时的值。

问题似乎是“时间”和“速度”本身的值经常重复,如您在示例中所见。但是,(时间,速度)对只有一个唯一的实例。

我想:

  1. 绘制3D图形。也许是X =时间,Y =速度,Z = Cxx的网格或曲面图
  2. 绘制二维热图,其中Cxx将代表热量值(大小),X =时间,Y =速度。
  3. 使用meshgrid将读取的Z值映射到XY点的网格上。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

如果没有要绘制的数据,很难回答您的问题。但是,通常要绘制IR ^ 2函数,例如z =(x,y),大多数绘图工具都要求x,y,z为2D数组或矩阵。您的数据已经为此准备好了,因为列中的值重复。因此,您只需要将数据列重塑为2D数组即可。请使用您的数据更新timevelocitycxxtime_pointsvelocity_points,并检查以下代码是否对您有用。

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

# some data
time = [-1.0, -0.999, -0.998, 0.998, 0.999, 1.0, -1.0, -0.999, -0.998, 0.998, 0.999, 1.0]
velocity = [-10000, -10000, -10000, -10000, -10000, -10000, -5000, -5000, -5000, -5000, -5000, -5000]
cxx = [0.000, 0.010, 0.011, 0.011, 0.010, 0.000, 0.000, 0.050, 0.055, 0.055, 0.050, 0.000]
time_points = 6 # -1.0, -0.999, -0.998, 0.998, 0.999, 1.0
velocity_points = 2 # -10000, -5000

# reshape data into matrices
x = np.reshape(time, (velocity_points, time_points))
y = np.reshape(velocity, (velocity_points, time_points))
z = np.reshape(cxx, (velocity_points, time_points))

# 1.1. plot a 3d graph (surface plot)
fig = plt.figure(1)
ax = fig.gca(projection='3d')
ax.plot_surface(x, y, z)
ax.set_xlabel('Time')
ax.set_ylabel('Velocity')
ax.set_zlabel('Cxx')

# 1.2. plot a 3d graph (surface plot) with a colormap and colorbar
fig = plt.figure(2)
ax = fig.gca(projection='3d')
surf = ax.plot_surface(x, y, z, cmap='jet')
plt.colorbar(surf)
ax.set_xlabel('Time')
ax.set_ylabel('Velocity')
ax.set_zlabel('Cxx')

# 2. heatmap with colorbar
fig = plt.figure(3)
ax = fig.gca()
plt.contourf(x, y, z, cmap='jet')
cbar = plt.colorbar()
ax.set_xlabel('Time')
ax.set_ylabel('Velocity')
cbar.set_label('Cxx')

# 3. direct view of Cxx values in a grid
fig = plt.figure(4)
ax = fig.gca()
plt.imshow(z, cmap='jet', interpolation='nearest')
cbar = plt.colorbar()
ax.set_xlabel('Time Index')
ax.set_ylabel('Velocity Index')
cbar.set_label('Cxx')

# show
plt.show()