You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

pyplot设置Times New Roman字体后负号显示异常问题求助

解决Matplotlib设置Times New Roman后负号不显示的问题

我之前踩过一模一样的坑!当你把全局字体改成Times New Roman后负号消失或显示异常,主要是这两个原因:

问题根源

  • Times New Roman是西文字体,默认没有包含Unicode负号的字形(Matplotlib默认用的是Unicode的而非ASCII的-
  • Matplotlib的axes.unicode_minus参数默认开启,会强制使用Unicode负号,而Times New Roman无法渲染这个符号,就会变成方块或者直接不显示

亲测有效的解决办法

1. 最简单的方案:关闭Unicode负号渲染

直接在设置字体后加一行参数配置,让Matplotlib用ASCII负号代替Unicode负号,Times New Roman完美支持这个符号:

import matplotlib.pyplot as plt

# 设置全局字体为Times New Roman
plt.rcParams["font.family"] = "Times New Roman"
# 关键:关闭unicode_minus,切换到ASCII负号
plt.rcParams['axes.unicode_minus'] = False

# 测试示例
plt.plot([-2, -1, 0, 1, 2], [4, 1, 0, 1, 4])
plt.title('Test Plot', fontsize=14)
plt.show()

2. 兼容更多场景:指定字体备选列表

如果你的图里还有其他特殊符号(比如希腊字母),可以给字体族加个备选,确保缺失的字形能被其他字体补上:

plt.rcParams['font.family'] = ['Times New Roman', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

DejaVu Sans是Matplotlib默认字体之一,对各种符号支持很好,和Times New Roman的风格也比较协调。

3. 精准控制:单独给元素指定字体(适合复杂场景)

如果全局设置影响了其他元素,或者系统找不到Times New Roman的默认路径,可以手动指定字体文件路径,单独给坐标轴、标题等元素设置字体:

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

# 手动指定Times New Roman的字体文件路径(Windows示例,Linux/macOS自行调整)
tnr_font = FontProperties(fname='C:/Windows/Fonts/times.ttf', size=12)

plt.plot([-1, 0, 1], [0, 1, 0])
# 给坐标轴标签和标题单独设置字体
plt.xlabel('X Value', fontproperties=tnr_font)
plt.ylabel('Y Value', fontproperties=tnr_font)
plt.title('Custom Font Test', fontproperties=tnr_font)
# 别忘了关闭unicode_minus
plt.rcParams['axes.unicode_minus'] = False
plt.show()

效果对比

默认字体效果:负号正常显示,但字体是Matplotlib默认的无衬线字体
未处理的Times New Roman效果:字体切换成功,但负号变成空白方块或消失
处理后的效果:Times New Roman字体正常显示,负号也完美渲染

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

火山引擎 最新活动