如何转换4列数据以制作带第四维颜色的Plotly 3D曲面图
Plotly 3D曲面图(含第四维颜色映射)实现修正
原代码的核心问题
- 直接过滤删除
selcperc维度,丢失了第四维可用于颜色映射的数据源 - 透视表处理时移除
mperiod索引、跳过首行数据,会导致X/Y轴刻度和矩阵坐标错位,无法和实际参数值对应 - 未显式指定
go.Surface的x/y轴取值、独立颜色矩阵,默认仅用Z值同时承担高度和颜色映射,无法实现四维参数的独立展示
数据结构转换规则
符合Plotly Surface要求的矩阵结构不需要手动裁剪索引,核心步骤为:
- 提取三个独立维度的唯一有序值:将
rocperiod作为X轴序列、mperiod作为Y轴序列 - 用
np.meshgrid将1D的X、Y序列展开为2D坐标网格,匹配曲面图要求的矩阵形状 - 将连续值
value转换为同形状矩阵,作为曲面的高度(Z轴) - 将离散值
selcperc转换为同形状矩阵,作为独立的颜色映射源
修正后可直接运行的代码
import pandas as pd import numpy as np import plotly.graph_objects as go def plotly_4d(data): df1 = pd.DataFrame.from_records( data, columns=['selcperc', 'mperiod', 'rocperiod', 'value'] ) # 提取有序轴刻度,按参数从小到大排序匹配原始计算逻辑 x_vals = sorted(df1['rocperiod'].unique()) y_vals = sorted(df1['mperiod'].unique()) # 生成2D网格坐标 X, Y = np.meshgrid(x_vals, y_vals) # 按轴顺序对齐Z轴高度矩阵、第四维颜色矩阵 z_matrix = df1.pivot( index='mperiod', columns='rocperiod', values='value' ).loc[y_vals, x_vals].values color_matrix = df1.pivot( index='mperiod', columns='rocperiod', values='selcperc' ).loc[y_vals, x_vals].values fig = go.Figure( data=[ go.Surface( x=X, y=Y, z=z_matrix, surfacecolor=color_matrix, contours_z=dict( show=True, usecolormap=True, highlightcolor="limegreen", project_z=True ) ) ] ) fig.update_layout( title_text="Analysis of Strategy", autosize=False, width=700, height=700, margin=dict(l=65, r=50, b=65, t=90) ) fig.show() data = [[1, 100, 100, 39.75640778351649], [1, 100, 110, 9.872282288628153], [1, 100, 120, 9.872282288628153], [1, 100, 130, 9.642593626259359], [1, 110, 100, 8.080838244365983], [1, 110, 110, 8.080838244365983], [1, 110, 120, 8.080838244365983], [1, 110, 130, 7.800644723300946], [1, 120, 100, 16.665716278906633], [1, 120, 110, 16.665716278906633], [1, 120, 120, 16.665716278906633], [1, 120, 130, 16.24384694969096], [1, 130, 100, 5.48409659630341], [1, 130, 110, 5.48409659630341], [1, 130, 120, 5.48409659630341], [1, 130, 130, 5.48409659630341], [2, 100, 100, 28.07034496404147], [2, 100, 110, 2.4858848187807294], [2, 100, 120, 2.4858848187807294], [2, 100, 130, 2.5146638062505695], [2, 110, 100, 2.2346947747962775], [2, 110, 110, 2.2346947747962775], [2, 110, 120, 2.2346947747962775], [2, 110, 130, 2.257673458249152], [2, 120, 100, 1.3453241481836469], [2, 120, 110, 1.3453241481836469], [2, 120, 120, 1.3453241481836469], [2, 120, 130, 1.3663313544445679], [2, 130, 100, 0.9013560706526865], [2, 130, 110, 0.9013560706526865], [2, 130, 120, 0.9013560706526865], [2, 130, 130, 0.9013560706526865]] plotly_4d(data)
各维度参数绑定说明
x:绑定rocperiod维度的网格坐标,对应X轴展示的实际参数值y:绑定mperiod维度的网格坐标,对应Y轴展示的实际参数值z:绑定value维度的矩阵值,对应Z轴的曲面高度surfacecolor:绑定selcperc维度的同形状矩阵,实现第四维参数到曲面颜色的独立映射,不会和Z轴高度的颜色规则绑定
内容的提问来源于stack exchange,提问作者the_hook86
相关产品推荐
相关产品推荐

