You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly Python导出PNG图片时多字体样式失效问题求助

解决Plotly导出PNG时多种字体样式丢失的问题

当Plotly在浏览器中渲染正常但导出PNG时丢失特殊字体,核心原因是导出工具(Kaleido/Orca)的独立渲染环境无法自动识别本地系统字体,即使字体已安装。以下是具体解决方法:

1. 切换到Kaleido(推荐替代Orca)

Orca已停止维护,Plotly官方推荐使用Kaleido作为导出工具,先确保安装:

pip install kaleido

2. 显式指定字体文件路径

Kaleido不会自动扫描系统字体,需要直接提供字体文件的路径。先找到你本地的字体文件位置:

  • Windows:C:\Windows\Fonts\ariblk.ttf(Arial Black)、C:\Windows\Fonts\arial.ttf(Arial)
  • macOS:/Library/Fonts/Arial Black.ttf、/Library/Fonts/Arial.ttf
  • Linux:先安装微软字体包sudo apt install ttf-mscorefonts-installer,路径为/usr/share/fonts/truetype/msttcorefonts/Arial_Black.ttf、/usr/share/fonts/truetype/msttcorefonts/Arial.ttf

方法一:在图表布局中指定字体源

修改代码,通过tickfont的src参数直接关联字体文件:

import pandas as pd
import plotly.express as px

df = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv")

fig = px.histogram(df, x="Age", color="Sex")

# 全局字体设为Arial,Y轴刻度显式指定Arial Black的字体文件
fig.update_layout(
    font_family="Arial",
    yaxis={
        "tickfont": {
            "family": "Arial Black",
            "src": "C:\\Windows\\Fonts\\ariblk.ttf"  # 替换为你的实际路径,Windows注意转义反斜杠
        }
    }
)

fig.show()
fig.write_image("test_image.png")

方法二:通过Kaleido Scope加载字体

如果需要复用字体配置,可以创建Kaleido Scope并加载所需字体:

import pandas as pd
import plotly.express as px
from kaleido.scopes.plotly import PlotlyScope

df = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv")
fig = px.histogram(df, x="Age", color="Sex")

fig.update_layout(font_family="Arial")
fig.update_yaxes(tickfont_family="Arial Black")

# 创建Scope并加载字体文件
scope = PlotlyScope(
    fonts=[
        "C:\\Windows\\Fonts\\arial.ttf",
        "C:\\Windows\\Fonts\\ariblk.ttf"
    ]
)

# 使用Scope导出图片
scope.transform(fig, format="png", path="test_image.png")

3. 通用化处理(可选)

可以将字体文件复制到项目目录(比如新建fonts文件夹),这样路径不受系统限制,适合跨环境使用:

# 假设字体文件放在项目的fonts目录下
"src": "./fonts/ariblk.ttf"

内容的提问来源于stack exchange,提问作者nsis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:45:32