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

使用mpld3保存HTML时样式与Jupyter显示不一致的问题

问题:mpld3导出的HTML图表与Jupyter显示样式不一致

我在用mpld3把matplotlib图表导出成HTML文件时,发现导出后的样式和Jupyter里显示的完全对不上:

  • 文本变成了Times New Roman字体
  • Y轴没自动使用科学计数法,导致刻度值过长盖住了Y轴标签
  • 整体文本尺寸偏小

Jupyter里的图表显示完全符合预期,但保存后的HTML就出现这些问题,怎么才能让两者样式完全一致呢?

我的代码如下:

# Global imports
import csv
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import mpld3

x = []
y = []

fig = figure(figsize=(12, 9))
ax = fig.gca()

for key, val in passenger_km_dict.items():
    x.append(int(key))
    y.append(int(val) * 1000000)
#print(x)
#print(y)

ax.plot(x, y)
ax.set_xlabel('Year') # Set some labels
ax.set_ylabel('Kilometres (1 ** 11)')
ax.set_title('Passenger Car Kilometres per Year from 1970 through 2017')

mpld3.save_html(fig,'Graphics\plot_passenger_km_per_year.html', template_type='simple')
#mpld3.show(fig)

解决方案

要让mpld3导出的HTML和Jupyter显示效果一致,需要从matplotlib全局样式配置和mpld3保存参数两方面调整:

1. 统一字体与文本尺寸

Jupyter默认使用无衬线字体和特定的文本大小,我们可以通过plt.rcParams提前配置matplotlib的全局样式,让mpld3渲染时继承这些设置:

# 配置全局样式,匹配Jupyter默认效果
plt.rcParams.update({
    'font.family': 'sans-serif',  # Jupyter默认无衬线字体
    'font.size': 12,              # 基础文本尺寸
    'axes.labelsize': 14,         # 轴标签大小
    'axes.titlesize': 16,         # 图表标题大小
    'xtick.labelsize': 12,        # X轴刻度文本大小
    'ytick.labelsize': 12         # Y轴刻度文本大小
})

2. 强制Y轴使用科学计数法

mpld3有时候不会自动继承matplotlib的刻度格式,我们可以手动设置Y轴的科学计数法,避免刻度值过长覆盖标签:

from matplotlib.ticker import ScalarFormatter

# 强制Y轴启用科学计数法
ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0))

3. 使用Jupyter兼容的模板

你之前用的template_type='simple'是极简模板,和Jupyter的渲染环境差异很大,改用'notebook'模板会更贴近Jupyter的显示效果:

# 注意:Windows路径建议用正斜杠,避免转义问题
mpld3.save_html(fig, 'Graphics/plot_passenger_km_per_year.html', template_type='notebook')

完整修改后的代码

# Global imports
import csv
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
from matplotlib.ticker import ScalarFormatter
import mpld3

# 配置全局样式,匹配Jupyter默认效果
plt.rcParams.update({
    'font.family': 'sans-serif',
    'font.size': 12,
    'axes.labelsize': 14,
    'axes.titlesize': 16,
    'xtick.labelsize': 12,
    'ytick.labelsize': 12
})

x = []
y = []

fig = figure(figsize=(12, 9))
ax = fig.gca()

for key, val in passenger_km_dict.items():
    x.append(int(key))
    y.append(int(val) * 1000000)

ax.plot(x, y)
ax.set_xlabel('Year')
ax.set_ylabel('Kilometres (1 ** 11)')
ax.set_title('Passenger Car Kilometres per Year from 1970 through 2017')

# 强制Y轴启用科学计数法
ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0))

# 使用notebook模板保存,贴近Jupyter显示效果
mpld3.save_html(fig, 'Graphics/plot_passenger_km_per_year.html', template_type='notebook')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:08:47