一文解决Ubuntu/Windows中Python plt中英文字体混排显示报错/方框中文/非正常显示问题
·
1. Ubuntu系统
1. 将以下代码直接放在可视化代码的全局最前位置,其中的参数基于中文论文图片格式排版要求。
import matplotlib.font_manager as fm
font_path = "/usr/share/fonts/program_font/simsun.ttc"
fm.fontManager.addfont(font_path)
# 设置全局字体为 Times New Roman(用于英文、数字、坐标轴)
plt.rcParams.update({
'font.family': ['Times New Roman', 'SimSun'],
'font.serif': ['Times New Roman', 'Liberation Serif', 'Times', 'serif'],
'font.size': 10,
'axes.titlesize': 11,
'axes.labelsize': 10,
'xtick.labelsize': 9,
'ytick.labelsize': 9,
'legend.fontsize': 9,
'lines.linewidth': 0.5,
'axes.linewidth': 0.5,
'xtick.major.width': 0.5,
'ytick.major.width': 0.5,
'svg.fonttype': 'none' # 保留文字为可编辑文本
})
2. font_path 这一句会报错,是因为 ubuntu 没有自带 simsun (宋体),参照链接进行常用字体安装program_font 安装常用字体(当然也可以参照其他方法),或者已经安装字体,则替换为你的simsun.ttc目录。
3. 你可以通过如下代码查看当前系统存在哪些字体:
import matplotlib.font_manager as fm
for f in fm.findSystemFonts():
print(f)
4. 绘图,会自动使用 宋体 + Times New Roman
plt.plot(x_list, y_list, label="数据")
plt.axis('equal')
lt.title("轨迹数据")
plt.xlabel("X [m]")
plt.ylabel("Y [m]")
plt.legend()
2. Windows 系统
1. 在全局位置首先设置英文以及数字字体为 Times New Roman
import matplotlib.pyplot as plt
from matplotlib import font_manager
# 全局设置英文/数字字体
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Times New Roman']
# 在需要中文的地方,单独指定 fontproperties
# 创建需要使用的中文字体对象
zh_font = font_manager.FontProperties(fname=r"C:/Windows/Fonts/simsun.ttc", size=10)
2. 在中文具体位置指定中文字体,其他绘图对象则默认为全局 Times New Roman
plt.xlabel('位移 $[\mathrm{m}]$', fontproperties=zh_font)
plt.ylabel('数量', fontproperties=zh_font)
3. 琢磨了很久, Windows 似乎很难实现 中文加英文 同一绘图对象的混排,例如 上述代码中的 横坐标 "位移 [m]", 欢迎交流。

更多推荐



所有评论(0)