Plotly 中的静态图像导出#

资料来源:

Plotly 允许您保存您图形的静态图像。将图像保存到本地计算机,或作为静态图像嵌入到您的 Jupyter 笔记本中。

安装依赖项#

静态图像生成需要 Kaleido。使用 pip 安装 Kaleido:

pip install --upgrade kaleido

或者使用 conda:

conda install -c conda-forge python-kaleido

Kaleido 使用 Chrome 进行静态图像生成,它会寻找运行其程序的机器上已安装的兼容版本的 Chrome(或 Chromium)。如果你没有安装 Chrome,可以按照你的操作系统说明直接从 Google 安装。

Plotly 还提供了从命令行安装 Chrome 的方法:

plotly_get_chrome

将图像写入文件#

Plotly 图有 write_image 方法可以将其写入文件。write_image 支持 PNG、JPEG、WebP、SVG 和 PDF 格式。

from pathlib import Path

temp_dir = Path.cwd() / "temp"
temp_dir.mkdir(exist_ok=True)
import plotly.express as px
data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')
fig.write_image(temp_dir/"fig1.png")

写入多个图像#

plotly.io 提供了 write_images 函数,用于将多个图形写入图像。使用 write_images 比多次调用 fig.write_image 更快。

write_images 以图形对象列表或表示图形的字典作为其第一个参数 fig 。第二个参数 file 是导出路径的列表。这些路径可以指定为 str 或 pathlib.Path 对象。

import plotly.graph_objects as go
import plotly.express as px
import plotly.io as pio


fig1 = go.Figure(
    data=go.Scatter(x=[1, 2, 3], y=[4, 5, 6], mode='lines+markers'),
    layout=go.Layout(title='Line Chart')
)

fig2 = go.Figure(
    data=go.Bar(x=['A', 'B', 'C'], y=[10, 5, 15]),
    layout=go.Layout(title='Bar Chart')
)

fig3 = px.pie(
    values=[30, 20, 10, 40],
    names=['A', 'B', 'C', 'D'],
    title='Pie Chart'
)
export_images = temp_dir/'export_images'
export_images.mkdir()
pio.write_images(
    fig=[fig1, fig2, fig3],
    file=[export_images/im for im in ['line_chart.png', 'bar_chart.png', 'pie_chart.png']]
)

获取图像为字节#

除了导出到文件外,Plotly 图形还支持转换为字节对象。要将图形转换为 PNG 字节对象,请调用图形的 to_image 方法,并传入 format 。

import plotly.express as px
data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')
img_bytes = fig.to_image(format="png")

使用 IPython.display.Image 显示了 bytes 对象:

from IPython.display import Image
Image(img_bytes)

指定图像尺寸和比例#

除了图像格式外, to_image 和 write_image 函数还提供参数来指定图像的 width 和 height 在逻辑像素中。它们还提供了 scale 参数,可用于增加( scale > 1)或减少( scale < 1)生成图像的物理分辨率。

img_bytes = fig.to_image(format="png", width=600, height=350, scale=2)
Image(img_bytes)