[ PROMPT_NODE_27010 ]
export-interactivity
[ SKILL_DOCUMENTATION ]
# 导出与交互
## 静态图像导出
### 安装
静态图像导出需要 Kaleido:
bash
uv pip install kaleido
Kaleido v1+ 需要系统安装 Chrome/Chromium。
### 支持的格式
- **光栅图**: PNG, JPEG, WebP
- **矢量图**: SVG, PDF
### 写入文件
python
import plotly.express as px
fig = px.scatter(df, x='x', y='y')
# 格式根据扩展名自动推断
fig.write_image('chart.png')
fig.write_image('chart.pdf')
fig.write_image('chart.svg')
# 显式指定格式
fig.write_image('chart', format='png')
### 转换为字节流
python
# 获取图像字节流
img_bytes = fig.to_image(format='png')
# 在 Jupyter 中显示
from IPython.display import Image
Image(img_bytes)
# 手动保存到文件
with open('chart.png', 'wb') as f:
f.write(img_bytes)
### 自定义导出
python
fig.write_image(
'chart.png',
format='png',
width=1200,
height=800,
scale=2 # 更高的分辨率
)
### 设置导出默认值
python
import plotly.io as pio
pio.kaleido.scope.default_format = 'png'
pio.kaleido.scope.default_width = 800
pio.kaleido.scope.default_height = 600
pio.kaleido.scope.default_scale = 2
### 导出多个图形
python
import plotly.io as pio
# 仅限 Kaleido v1+
pio.write_images(
fig=[fig1, fig2, fig3],
file=['chart1.png', 'chart2.png', 'chart3.png']
)
## 交互式 HTML 导出
### 基础导出
python
# 完整的独立 HTML
fig.write_html('interactive_chart.html')
# 在浏览器中打开
fig.show()
### 文件大小控制
python
# 嵌入完整库 (~5MB 文件)
fig.write_html('chart.html', include_plotlyjs=True)
# CDN 引用 (~2KB 文件,需要联网)
fig.write_html('chart.html', include_plotlyjs='cdn')
# 本地引用 (需要在同一目录下有 plotly.min.js)
fig.write_html('chart.html', include_plotlyjs='directory')
# 不包含库 (用于嵌入到已有的包含 Plotly.js 的 HTML 中)
fig.write_html('chart.html', include_plotlyjs=False)
### HTML 配置
python
fig.write_html(
'chart.html',
config={
'displayModeBar': True,
'displaylogo': False,
'toImageButtonOptions': {
'format': 'png',
'filename': 'custom_image',
'height': 800,
'width': 1200,
'scale': 2
}
}
)
### 嵌入到模板中
python
# 仅获取 div (不包含完整 HTML 结构)
html_div = fig.to_html(
full_html=False,
include_plotlyjs='cdn'