You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将二维线图切片生成三维曲面图或等高线图?

解决思路与代码示例

核心逻辑

你的需求本质是把一维时序数据转换成二维矩阵,才能满足3D曲面/等高线图的输入要求:

  • X轴:整秒时间(900到11496秒)
  • Y轴:每秒内的采样点序号(0到199,对应每秒200个观测值)
  • Z轴:对应采样点的强度值

通过这种维度转换,就能构建出绘图所需的二维Z矩阵。

数据预处理步骤

  1. 给原始数据添加两个衍生列:
    • second:提取每个观测值对应的整秒时间(比如对Time列取整数,或按每200个数据点分组标记秒数)
    • sample_idx:标记每个观测值在当前秒内的位置(0到199循环)
  2. 用透视表将数据转成二维结构:行是second,列是sample_idx,值是intensity,得到标准的Z矩阵。

示例代码(适配你的虚拟数据场景)

调整虚拟数据模拟真实场景(10秒,每秒10个采样点,对应真实场景的每秒200个采样):

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

# 生成模拟数据:10秒,每秒10个采样点
total_samples = 10 * 10
dummy_time = np.repeat(range(900, 910), 10)  # 900到909秒,每个秒重复10次
dummy_intensity = np.random.randint(1, 100000, total_samples)

df = pd.DataFrame({
    "time": dummy_time,
    "intensity": dummy_intensity
})

# 1. 添加衍生列
# 标记每个采样点在当前秒内的索引(0-9)
df["sample_idx"] = df.groupby("time").cumcount()
# 把time作为X轴的秒数(直接用原time列的整数值)
df["second"] = df["time"]

# 2. 转成二维Z矩阵
z_matrix = df.pivot(index="second", columns="sample_idx", values="intensity")

# 3. 准备X、Y网格
x = z_matrix.index.values
y = z_matrix.columns.values
X, Y = np.meshgrid(x, y)
# 转置Z以匹配meshgrid后的维度
Z = z_matrix.values.T

# 4. 绘制3D曲面图
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')

ax.set_xlabel('Time (seconds)')
ax.set_ylabel('Sample Index in Second')
ax.set_zlabel('Intensity')
plt.title('3D Surface Plot of Time vs Sample Index vs Intensity')
plt.show()

# 5. 绘制等高线图
plt.figure(figsize=(10, 6))
contour = plt.contourf(X, Y, Z, cmap='viridis')
plt.xlabel('Time (seconds)')
plt.ylabel('Sample Index in Second')
plt.title('Contour Plot of Time vs Sample Index vs Intensity')
plt.colorbar(contour, label='Intensity')
plt.show()

真实数据适配注意事项

  • 真实数据中每秒恰好200个观测值,groupby("time").cumcount()会自动生成0-199的索引,无需额外调整
  • 如果原始Time列带小数(如900.005、900.01),用df["second"] = df["time"].astype(int)提取整秒时间即可
  • 若数据存在缺失,透视后出现的NaN可通过z_matrix.fillna(0)或插值方法填充

内容的提问来源于stack exchange,提问作者jhupiterz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 08:34:55