【一分钟解决】Matplotlib 中英文混排多字体设置问题

⚠️ 本文讨论基于 macOS 系统,部分示例代码可能需要根据操作系统微调。

中西混排示例

样图

代码

import matplotlib.pyplot as plt

config = {
    "font.family": "serif",  # 使用衬线体
    "font.serif": ["SimSun"],  # 全局默认使用衬线宋体
    "font.size": 14,  # 五号,10.5磅
    "axes.unicode_minus": False,
    "mathtext.fontset": "stix",  # 设置 LaTeX 字体,stix 近似于 Times 字体
}
plt.rcParams.update(config)


fig, ax = plt.subplots(figsize=(5, 5))
ax.plot([i / 10.0 for i in range(10)], [i / 10.0 for i in range(10)])
# 中西混排,西文使用 LaTeX 罗马体
ax.set_title("能量随时间变化\n$\mathrm{Change\ in\ energy\ over\ time}$")
ax.set_xlabel("时间($\mathrm{s}$)")
ax.set_ylabel("能量($\mathrm{J}$)")

# 坐标系标签使用西文字体
ticklabels_style = {
    "fontname": "Times New Roman",
    "fontsize": 12,  # 小五号,9磅
}
plt.xticks(**ticklabels_style)
plt.yticks(**ticklabels_style)
plt.legend(["测试曲线"])
plt.show()

解决思路

  1. 设置全局默认字体为宋体(SimSun);
  2. 设置 LaTeX 默认使用 STIX 字体,在中文环境中使用 $\mathrm{...}$ 转换西文为 STIX 罗马体;
  3. 设置坐标轴标签字体为 Times New Roman。

💡 STIX fonts (with are designed to blend well with Times).

扩展

查看可调用字体

上述代码 "font.serif": ["SimSun"]中的字体名可通过以下代码块得到:

# find_fonts.py
from matplotlib import font_manager

for font in font_manager.fontManager.ttflist:
    print(font.name)

💡 在终端中使用 python find_fonts.py | fzf 即可交互搜索可用字体❗️

参考链接

  1. 解决python中matplotlib中文乱码 for Mac - 简书
  2. Matplotlib 中英文及公式字体设置 - 知乎
  3. python - How do I change the axis tick font in a matplotlib plot when rendering using Latex? - Stack Overflow
  • 16
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值