matplotlib中英文设置不同字体的方法

Python与matplotlib版本

# 导入所需库
import sys
import numpy as np
import matplotlib as plt

# ========== 输出版本信息 ==========
print("=== 运行环境版本信息 ===")
# Python 版本
print(f"Python 版本: {sys.version}")
# numpy 版本
print(f"numpy 版本: {np.__version__}")
# matplotlib 版本
print(f"matplotlib 版本: {plt.__version__}")
print("="*30 + "\n")

我的软件版本

=== 运行环境版本信息 ===
Python 版本: 3.11.1 (tags/v3.11.1:a7a450f, Dec  6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)]
numpy 版本: 1.24.3
matplotlib 版本: 3.9.3
==============================

问题描述

通常在绘制图表的过程中, 我们将中文设置为宋体, 英文设置为Times New Roman, 然而matplotlib如果不做额外的设置, 需要输出的中文内容将会变为方框.


import numpy as np
import matplotlib.pyplot as plt



# 1. 生成x轴数据:范围从0到2π,生成1000个点(点数越多曲线越平滑)
x = np.linspace(0, 2 * np.pi, 1000)

# 2. 计算sin和cos函数值
y_sin = np.sin(x)
y_cos = np.cos(x)

# 3. 创建画布并绘制图像
plt.figure(figsize=(10, 6))  # 设置画布大小:宽10英寸, 高6英寸

# 绘制sin曲线, 设置颜色、线型、标签(用于图例)
plt.plot(x, y_sin, color='red', linestyle='-', linewidth=2, label='sin(x)')
# 绘制cos曲线,设置颜色、线型、标签
plt.plot(x, y_cos, color='blue', linestyle='--', linewidth=2, label='cos(x)')

# 4. 添加标注元素
plt.xlabel('x 轴(弧度)', fontsize=12)  # x轴标签
plt.ylabel('y 轴(函数值)', fontsize=12)  # y轴标签
plt.title('sin(x) 和 cos(x) 函数图像(0 ≤ x ≤ 2π)', fontsize=14, fontweight='bold')  # 标题
plt.legend(loc='best', fontsize=11)  # 图例,loc='best'表示自动选择最佳位置

# 5. 优化图像显示(添加网格、设置坐标轴范围)
plt.grid(True, alpha=0.3)  # 添加网格,alpha设置透明度
plt.ylim(-1.2, 1.2)        # y轴范围(让图像上下有留白, 更美观)
plt.xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi], 
           ['0', 'π/2', 'π', '3π/2', '2π'])  # x轴刻度显示为π的形式

# 6. 显示图像
plt.show()

通常上述代码运行完成后, 也会在命令行输出警告提示:

C:\Users\bushuo\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py:861: UserWarning: Glyph 36724 (\N{CJK UNIFIED IDEOGRAPH-8F74}) missing from font(s) DejaVu Sans.
  func(*args)
C:\Users\bushuo\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py:861: UserWarning: Glyph 20989 (\N{CJK UNIFIED IDEOGRAPH-51FD}) missing from font(s) DejaVu Sans.
  func(*args)
C:\Users\bushuo\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py:861: UserWarning: Glyph 25968 (\N{CJK UNIFIED IDEOGRAPH-6570}) missing from font(s) DejaVu Sans.
  func(*args)
C:\Users\bushuo\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py:861: UserWarning: Glyph 20540 (\N{CJK UNIFIED IDEOGRAPH-503C}) missing from font(s) DejaVu Sans.
  func(*args)
C:\Users\bushuo\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py:861: UserWarning: Glyph 21644 (\N{CJK UNIFIED IDEOGRAPH-548C}) missing from font(s) DejaVu Sans.
  func(*args)
C:\Users\bushuo\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py:861: UserWarning: Glyph 22270 (\N{CJK UNIFIED IDEOGRAPH-56FE}) missing from font(s) DejaVu Sans.
  func(*args)
C:\Users\bushuo\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py:861: UserWarning: Glyph 20687 (\N{CJK UNIFIED IDEOGRAPH-50CF}) missing from font(s) DejaVu Sans.
  func(*args)
C:\Users\bushuo\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py:861: UserWarning: Glyph 24359 (\N{CJK UNIFIED IDEOGRAPH-5F27}) missing from font(s) DejaVu Sans.
  func(*args)
C:\Users\bushuo\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py:861: UserWarning: Glyph 24230 (\N{CJK UNIFIED IDEOGRAPH-5EA6}) missing from font(s) DejaVu Sans.
  func(*args)

上述警告的核心意思是: matplotlib默认使用的DejaVu Sans字体不包含中文(CJK统一汉字)字符, 导致代码中设置的中文标签, 标题不妨正常渲染, 系统在尝试绘制中文字符时找不到对应的字体字型, 因此抛出警告.

missing from font(s) DejaVu Sans: 表示这些字符在DejaVu Sans字体中不存在, DejaVu Sans 是 matplotlib 英文环境的默认字体, 仅支持拉丁/希腊等字符, 不支持中文.

下面是一个UNICODE转中文的网站, 可以将UNICODE编码转换为汉字.

在线 Unicode 编码转换 | 菜鸟工具

解决方法

方法一, 修改字体配置代码

在程序导入matplotlib库的代码后面, 添加如下代码


# 设置中文字体(解决matplotlib默认不显示中文的问题)
# 字体全局配置
# 设置全局字体家族, 优先使用Times New Roman, 备用宋体(Simsun)
plt.rcParams['font.family'] = 'Times New Roman, SimSun'
# 设置数学公式(mathtext)的字体集为stix(适配Times New Roman, 避免公式字体混乱)
# 和Times New Roman差别不大
plt.rcParams['mathtext.fontset'] = 'stix'
plt.rcParams['axes.unicode_minus'] = False

设置后的绘图结果

方法二, 修改配置文件

  1. 找到配置文件的位置

import matplotlib as plt
print(plt.matplotlib_fname())

Windows通常在: C:\Users\用户名\AppData\Local\Programs\Python\Python311\Lib\site-packages\matplotlib\mpl-data\matplotlibrc, 或者C:\Users\你的用户名\.matplotlib\matplotlibrc

  1. 然后用记事本打开该文件, 在 font.sans-serif 后面添加一个中文字体名称
  1. 这样全局都会是宋体;

  2. 如果需要中文是宋体, 英文是Times New Roman, 那么就需要修改font.family:, 并将英文字体写在中文字体前面, 如下图所示.

方法三, 安装一种Times New Roman + 宋体的字体, 然后指定该字体为全局字体

python绘图,中文设置为宋体,英文设置为新罗马_python宋体-CSDN博客

Python Matplotlib中文宋体+英文Times New Roman方法_times+simsun.ttf-CSDN博客

相关参考链接

Python画图设置宋体和新罗马Times New Roman_pycahrm绘制图像英文设置为times roman6号-CSDN博客

(17 封私信 / 80 条消息) 完美解决Python的matplotlib库中英文字体混显问题 - 知乎

(17 封私信 / 80 条消息) Matplotlib实现宋体(simsun)和Times New Roman混编 - 知乎

指定字体

matplotlib如何设置中文为宋体,英文为新罗马Times New Roman_matplotlib中文宋体,英文新罗马-CSDN博客

(17 封私信 / 80 条消息) Matplotlib 中文乱码解决方案教程 - 知乎

garrettj403/SciencePlots: Matplotlib styles for scientific plotting

如何使matplotlib同时使用宋体和Times New Roman | 鴻塵

python绘图,中文设置为宋体,英文设置为新罗马_python宋体-CSDN博客

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐