Plotly如何创建三维散点图和表面图?
解读
在 Jupyter 生态里,Plotly 是最常被面试官拿来验证候选人“能否把探索结果一键变成可交互报告”的库。三维散点图考你对高维数据降维或聚类结果的呈现能力;三维表面图则直接对应模型预测网格、响应面、期权波动率曲面等金融与工业场景。面试官不仅想看你会不会调 API,更想确认:
- 你是否知道在 Notebook 里用
plotly.offline.init_notebook_mode或fig.show("notebook")保证离线渲染; - 你是否理解
go.Scatter3d与go.Surface在数据形状上的本质区别——前者是“长表”,后者是“网格矩阵”; - 你是否能把交互控件(
updatemenus、sliders)与 Jupyter Widget 打通,实现“一个 Cell 搞定演示”。
知识点
- Plotly Python 包两种接口:
graph_objects(精细控制)与express(快速出图)。 - 三维坐标系下:
- 散点图用
go.Scatter3d(x=..., y=..., z=..., mode="markers", marker=dict(size=..., color=..., colorscale="Viridis", showscale=True)); - 表面图用
go.Surface(z=2D_array, x=1D_vector, y=1D_vector),其中 z 必须是 (m×n) 矩阵。
- 散点图用
- 在 JupyterLab 3+ 中,需装
jupyterlab-plotly扩展;Notebook 7 已内置 MIME renderer,无需额外魔法命令。 - 性能陷阱:散点超过 10^5 行时,用
scattergl或datashader预聚合;表面图超过 500×500 网格时,先用scipy.zoom重采样,避免前端卡死。 - 可复现性:用
pio.write_json(fig, "result.fig.json")把完整 Figure 序列化,git 只存 JSON,下次pio.read_json直接渲染,无需重跑模型。 - 与 ipywidgets 联动:
interactive_plot = go.FigureWidget(fig); def update_surface(alpha): ...; widgets.FloatSlider(...).observe(update_surface, "value"),实现“滑块调超参、三维图实时更新”。
答案
下面给出一段可直接粘进 Jupyter Notebook 的代码,既展示三维散点,又展示三维表面,并附带中文标题、色阶、交互按钮,符合国内面试官“跑通即可”的惯例:
# 0. 环境准备(国内清华源加速)
!pip install -i https://pypi.tuna.tsinghua.edu.cn/simple plotly pandas numpy scikit-learn
import plotly.graph_objects as go
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
# 1. 三维散点图:以 Iris 降维为例
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df["species"] = iris.target
pca = PCA(n_components=3)
coords = pca.fit_transform(df.iloc[:, :4])
scatter = go.Scatter3d(
x=coords[:, 0], y=coords[:, 1], z=coords[:, 2],
mode="markers",
marker=dict(
size=6,
color=df["species"],
colorscale="Viridis",
opacity=0.8,
showscale=True,
colorbar=dict(title="类别")
),
text=[iris.target_names[i] for i in df["species"]],
hovertemplate="%{text}<br>PC1=%{x:.2f}<br>PC2=%{y:.2f}<br>PC3=%{z:.2f}<extra></extra>"
)
layout_s = go.Layout(
title="Iris 数据集三维主成分散点图",
scene=dict(
xaxis_title="PC1",
yaxis_title="PC2",
zaxis_title="PC3"
),
margin=dict(l=0, r=0, t40, b=0)
)
fig_s = go.Figure(data=[scatter], layout=layout_s)
fig_s.show() # 在 Notebook 内嵌输出
# 2. 三维表面图:以二维高斯函数为例
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.exp(-(X**2 + Y**2))
surface = go.Surface(
x=x, y=y, z=Z,
colorscale="RdBu",
colorbar=dict(title="高度")
)
layout_f = go.Layout(
title="二维高斯函数三维表面图",
scene=dict(
xaxis_title="X",
yaxis_title="Y",
zaxis_title="Z"
),
margin=dict(l=0, r=0, t40, b=0)
)
fig_f = go.Figure(data=[surface], layout=layout_f)
fig_f.show()
# 3. 合并到同一图并添加交互按钮(加分项)
fig_combo = go.Figure()
fig_combo.add_trace(scatter)
fig_combo.add_trace(surface.update(visible=False)) # 默认隐藏表面
fig_combo.update_layout(
title="三维散点与表面图切换演示",
updatemenus=[
dict(
type="buttons",
direction="left",
buttons=[
dict(label="显示散点", method="update",
args=[{"visible": [True, False]},
{"title": "三维散点图"}]),
dict(label="显示表面", method="update",
args=[{"visible": [False, True]},
{"title": "三维表面图"}]),
dict(label="显示全部", method="update",
args=[{"visible": [True, True]},
{"title": "三维散点+表面图"}])
],
pad={"r": 10, "t": 10},
showactive=True,
x=0.1, xanchor="left", y=1.1, yanchor="top"
)
]
)
fig_combo.show()
运行后,面试官在 Notebook 里可直接点击按钮切换视图,体验“交互式报告”效果,通常即可通过技术面。
拓展思考
- 真实业务中,三维表面图往往来自模型网格预测。把
GridSearchCV的param_grid映射到 (x, y) 轴,把交叉验证平均得分映射到 z 轴,就能在 Notebook 里一眼看出超参敏感区,省去写 PPT。 - 如果数据量过大,可先用
vaex或polars做列式筛选,再用datashader.transfer_functions.shade生成 RGBA 图像,最后go.Image叠在go.Surface下方,实现“亿级点云+表面”的混合渲染。 - 在 JupyterHub 集群场景,给
go.Figure加config={"responsive": True, "displayModeBar": False},可防止学生误触缩放按钮导致前端崩溃;同时用plotly.io.write_html(fig, file, include_plotlyjs="cdn", full_html=False)生成 div 片段,嵌入公司内部的 Vue 报告平台,实现“Notebook→生产” 一条链。 - 面试反向提问:可问面试官“贵司的 Jupyter 环境是否已启用
jupyter-server-proxy?如果启用,我可以用Orbit或Dash-vtk把三维图转成 WebGL 2.0 流,直接嵌到 Lab 的右侧面板,实现零切换协作。” 这种回答能把话题引到基础设施,展示你对 Jupyter 生态的深度理解。