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

Plotly基于Pandas DataFrame绘制3D曲面图无结果求助

Plotly 3D曲面图无显示问题解决

核心问题:Plotly的go.Surface组件要求Z轴数据为二维矩阵格式,你直接传入了DataFrame的一维列数据,导致图表无法渲染。

解决步骤

  1. 转换数据格式:将长格式的DataFrame转换为宽格式的网格矩阵,确保每个X(P2)和Y(C2)的组合对应唯一的Z(Cycle Time Difference)值。
  2. 使用网格数据绘图:用转换后的二维矩阵作为Z轴输入,配合对应的X、Y网格数据生成曲面图。

修改后的完整代码

import pandas as pd
import numpy as np
import plotly.graph_objects as go

# 保留你的DataFrame创建逻辑
df_final = pd.DataFrame(list(zip(new_storage_p_two, new_storage_c_two, new_storage_result, backward_storage_result, gap)),
                        columns=['P2', 'C2', 'Cycle Time New Sequence', 'Cycle Time Backward Sequence','Cycle Time Difference'])

# 将数据转换为网格格式:P2为行索引,C2为列名,值为Cycle Time Difference
pivot_df = df_final.pivot_table(index='P2', columns='C2', values='Cycle Time Difference')

# 获取绘图所需的矩阵数据
x = pivot_df.columns.values  # C2的唯一值数组
y = pivot_df.index.values    # P2的唯一值数组
z = pivot_df.values          # 二维矩阵,对应每个P2-C2组合的差值

# 创建并显示曲面图
fig = go.Figure(data=[go.Surface(z=z, x=x, y=y)])
fig.update_traces(contours_z=dict(show=True, usecolormap=True, highlightcolor="limegreen", project_z=True))
fig.update_layout(title='Cycle Time Gap', autosize=False,
                  width=500, height=500,
                  margin=dict(l=65, r=50, b=65, t=90))
fig.show()

补充说明

  • 如果你的数据中存在重复的P2-C2组合,pivot_table默认会计算均值,你可以通过aggfunc参数指定聚合规则,例如aggfunc='first'取第一个值,aggfunc='max'取最大值。
  • 转换后的pivot_df是一个二维表格,行是P2的所有唯一值,列是C2的所有唯一值,单元格对应对应的Cycle Time Difference,这样的结构才能被go.Surface正确解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:10:22