# 如何使用Python和Plotly绘制3D图形

05/17 09:36

## 准备工作

pip install plotly

import plotly.graph_objects as go
import numpy as np

## 绘制散点图

# 生成示例数据
np.random.seed(42)
n_points = 100
x_data = np.random.rand(n_points)
y_data = np.random.rand(n_points)
z_data = np.random.rand(n_points)

# 创建散点图
fig = go.Figure(data=[go.Scatter3d(x=x_data, y=y_data, z=z_data, mode='markers')])
fig.update_layout(scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
title='3D Scatter Plot')
fig.show()

## 绘制曲面图

# 定义函数
def f(x, y):
return np.sin(x) * np.cos(y)

# 生成网格数据
x_grid = np.linspace(0, 2*np.pi, 50)
y_grid = np.linspace(0, 2*np.pi, 50)
x_grid, y_grid = np.meshgrid(x_grid, y_grid)
z_grid = f(x_grid, y_grid)

# 创建曲面图
fig = go.Figure(data=[go.Surface(z=z_grid, x=x_grid, y=y_grid)])
fig.update_layout(scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
title='3D Surface Plot')
fig.show()

## 绘制线框图

# 生成线框数据
theta = np.linspace(-4*np.pi, 4*np.pi, 100)
z_line = np.linspace(-2, 2, 100)
x_line = z_line * np.sin(theta)
y_line = z_line * np.cos(theta)

# 创建线框图
fig = go.Figure(data=[go.Scatter3d(x=x_line, y=y_line, z=z_line, mode='lines')])
fig.update_layout(scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
title='3D Wireframe Plot')
fig.show()

## 绘制3D条形图

# 生成示例数据
categories = ['A', 'B', 'C', 'D']
values = np.random.randint(1, 10, size=(len(categories), len(categories)))
x_bar, y_bar = np.meshgrid(np.arange(len(categories)), np.arange(len(categories)))
x_bar = x_bar.flatten()
y_bar = y_bar.flatten()
z_bar = np.zeros_like(x_bar)

# 设置条形图的高度
bar_heights = values.flatten()

# 创建3D条形图
fig = go.Figure(data=[go.Bar3d(x=x_bar, y=y_bar, z=z_bar, dx=1, dy=1, dz=bar_heights)])
fig.update_layout(scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
title='3D Bar Chart')
fig.show()

## 自定义图形样式

Plotly提供了丰富的自定义选项，可以调整图形的样式、布局和外观。你可以根据需要修改图形的颜色、线型、标签等属性，以满足特定的可视化需求。

# 自定义图形样式
fig.update_traces(marker=dict(color='rgb(255, 127, 14)', size=10),
selector=dict(mode='markers'))
fig.update_layout(scene=dict(xaxis=dict(backgroundcolor="rgb(200, 200, 230)",
gridcolor="white",
showbackground=True,
zerolinecolor="white"),
yaxis=dict(backgroundcolor="rgb(230, 200,230)",
gridcolor="white",
showbackground=True,
zerolinecolor="white"),
zaxis=dict(backgroundcolor="rgb(230, 230,200)",
gridcolor="white",
showbackground=True,
zerolinecolor="white")),
title='Customized 3D Scatter Plot')
fig.show()

## 交互式三维图形

Plotly还支持创建交互式的三维图形，让用户可以通过鼠标交互来探索数据。下面是一个交互式散点图的示例：

# 创建交互式散点图
fig = go.Figure(data=[go.Scatter3d(x=x_data, y=y_data, z=z_data, mode='markers')])
fig.update_layout(scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
title='Interactive 3D Scatter Plot')
fig.show()

## 导出图形

# 将图形导出为静态图片
fig.write_image("3d_plot.png")

# 将图形导出为交互式HTML文件
fig.write_html("3d_plot.html")

0 评论
1 收藏
0