本文目录导读:

我来为您展示如何使用Plotly创建三维散点图的完整案例。
基础三维散点图
import plotly.graph_objects as go
import numpy as np
# 生成随机数据
np.random.seed(42)
n_points = 500
x = np.random.randn(n_points)
y = np.random.randn(n_points)
z = np.random.randn(n_points)
# 创建3D散点图
fig = go.Figure(data=[go.Scatter3d(
x=x, y=y, z=z,
mode='markers',
marker=dict(
size=5,
color=z, # 根据z值着色
colorscale='Viridis', # 颜色渐变
opacity=0.8
)
)])
# 设置布局
fig.update_layout('基础3D散点图',
scene=dict(
xaxis_title='X轴',
yaxis_title='Y轴',
zaxis_title='Z轴'
)
)
fig.show()
带分类的3D散点图
import plotly.graph_objects as go
import pandas as pd
import numpy as np
# 生成模拟数据
np.random.seed(42)
n_points = 200
data = {
'x': np.random.randn(n_points) * 2,
'y': np.random.randn(n_points) * 2,
'z': np.random.randn(n_points) * 2,
'category': np.random.choice(['A', 'B', 'C', 'D'], n_points)
}
df = pd.DataFrame(data)
# 为每个类别创建单独的轨迹
colors = {'A': 'red', 'B': 'blue', 'C': 'green', 'D': 'purple'}
traces = []
for category, color in colors.items():
category_data = df[df['category'] == category]
trace = go.Scatter3d(
x=category_data['x'],
y=category_data['y'],
z=category_data['z'],
mode='markers',
name=category,
marker=dict(
size=6,
color=color,
opacity=0.7
)
)
traces.append(trace)
fig = go.Figure(data=traces)
fig.update_layout('带分类的3D散点图',
scene=dict(
xaxis_title='X轴',
yaxis_title='Y轴',
zaxis_title='Z轴'
),
legend_title='类别'
)
fig.show()
从真实数据创建3D散点图
import plotly.graph_objects as go
import plotly.express as px
from sklearn.datasets import load_iris
import pandas as pd
# 加载鸢尾花数据集
iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['species'] = iris.target_names[iris.target]
# 方法1: 使用plotly.graph_objects
fig1 = go.Figure()
for species_name in df['species'].unique():
species_data = df[df['species'] == species_name]
fig1.add_trace(go.Scatter3d(
x=species_data['sepal length (cm)'],
y=species_data['sepal width (cm)'],
z=species_data['petal length (cm)'],
mode='markers',
name=species_name,
marker=dict(
size=8,
opacity=0.7
)
))
fig1.update_layout('鸢尾花数据3D散点图',
scene=dict(
xaxis_title='花萼长度',
yaxis_title='花萼宽度',
zaxis_title='花瓣长度'
)
)
fig1.show()
# 方法2: 使用plotly.express (更简单)
fig2 = px.scatter_3d(
df,
x='sepal length (cm)',
y='sepal width (cm)',
z='petal length (cm)',
color='species','鸢尾花数据3D散点图 (Express)',
labels={
'sepal length (cm)': '花萼长度',
'sepal width (cm)': '花萼宽度',
'petal length (cm)': '花瓣长度'
}
)
fig2.show()
三维散点图的高级定制
import plotly.graph_objects as go
import numpy as np
# 生成螺旋数据
def generate_spiral(n_points=300):
t = np.linspace(0, 4*np.pi, n_points)
x = np.cos(t) * t
y = np.sin(t) * t
z = t / np.pi
color = t / (4*np.pi) # 用于颜色映射
return x, y, z, color
x, y, z, colors = generate_spiral()
# 创建高级定制3D散点图
fig = go.Figure(data=[go.Scatter3d(
x=x,
y=y,
z=z,
mode='markers',
marker=dict(
size=8, # 点的大小
color=colors, # 颜色值
colorscale='Rainbow', # 颜色方案
opacity=0.8, # 透明度
symbol='circle', # 点的形状
line=dict(
width=2,
color='white' # 点的边框
),
colorbar=dict(
title='位置',
titleside='right'
),
showscale=True
),
text=[f'点{i}: ({x[i]:.2f}, {y[i]:.2f}, {z[i]:.2f})'
for i in range(len(x))], # 悬停文本
hoverinfo='text'
)])
# 自定义布局
fig.update_layout({
'text': '3D螺旋散点图 (高级定制)',
'y': 0.95,
'x': 0.5,
'xanchor': 'center',
'yanchor': 'top'
},
scene=dict(
xaxis=dict(
title='X轴',
gridcolor='lightgray',
showbackground=True,
backgroundcolor='black'
),
yaxis=dict(
title='Y轴',
gridcolor='lightgray',
showbackground=True,
backgroundcolor='black'
),
zaxis=dict(
title='Z轴',
gridcolor='lightgray',
showbackground=True,
backgroundcolor='black'
),
camera=dict(
eye=dict(x=1.5, y=1.5, z=0.5) # 视角位置
),
aspectmode='cube' # 保持比例
),
paper_bgcolor='white',
height=600,
width=800,
showlegend=False
)
# 添加动画效果
fig.update_layout(
updatemenus=[{
'type': 'buttons',
'showactive': False,
'buttons': [{
'label': '自动旋转',
'method': 'animate',
'args': [None, {
'frame': {'duration': 50, 'redraw': True},
'fromcurrent': True,
'mode': 'immediate'
}]
}]
}]
)
fig.show()
与其他图表结合
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
# 创建子图:3D散点图 + 2D投影
np.random.seed(42)
n_points = 100
x = np.random.randn(n_points) * 2
y = np.random.randn(n_points) * 2
z = np.random.randn(n_points) * 2
colors = z # 使用z值作为颜色
fig = make_subplots(
rows=2, cols=2,
specs=[
[{'type': 'scatter3d', 'rowspan': 2}, {'type': 'scatter'}],
[None, {'type': 'scatter'}]
],
subplot_titles=('3D视图', 'X-Y投影', '', 'X-Z投影')
)
# 3D散点图
fig.add_trace(
go.Scatter3d(
x=x, y=y, z=z,
mode='markers',
marker=dict(size=5, color=colors, colorscale='Viridis'),
showlegend=False
),
row=1, col=1
)
# X-Y投影
fig.add_trace(
go.Scatter(
x=x, y=y,
mode='markers',
marker=dict(size=8, color=colors, colorscale='Viridis',
showscale=False),
showlegend=False
),
row=1, col=2
)
# X-Z投影
fig.add_trace(
go.Scatter(
x=x, y=z,
mode='markers',
marker=dict(size=8, color=colors, colorscale='Viridis',
showscale=False),
showlegend=False
),
row=2, col=2
)
fig.update_layout('3D散点图及其2D投影',
height=600,
width=900
)
fig.show()
主要特性说明
- 数据准备:使用NumPy生成模拟数据或从实际数据集加载
- 颜色定制:支持多种颜色方案(Viridis、Rainbow等)
- 交互功能:支持旋转、缩放、悬停查看数据点信息
- 多类别展示:可以按类别分组显示不同颜色的数据点
- 高级定制:自定义点的大小、透明度、边框等
- 子图组合:可以将3D散点图与2D投影结合展示
这些案例涵盖了Plotly创建三维散点图的主要场景,您可以根据实际需求进行修改和扩展。