这里写目录标题

问题描述

在Python利用Matplotlib绘图的时候,无法显示坐标轴上面的中文和标题里面的中文

import matplotlib.pyplot as plt
from numpy import square


squares = [1, 4, 9, 16, 25]
fig, ax = plt.subplots()
ax.plot(squares, linewidth = 3)

# 设置图表标题并给坐标轴加上标签。
ax.set_title("平方数", fontsize = 24)
ax.set_xlabel("值", fontsize = 14)
ax.set_ylabel("值的平方", fontsize = 14)

# 设置刻度标记的大小。
ax.tick_params(axis='both', labelsize =14 )


plt.show()

运行后如下界面

Python利用Matplotlib绘图无法显示中文字体的解决方案_python

报错信息

​A:\ProgramData\Anaconda3\envs\py39\lib\tkinter\__init__.py:814: UserWarning: Glyph 24179 (\N{CJK UNIFIED IDEOGRAPH-5E73}) missing from current font. func(*args)​

解决方法

在开头插入

import matplotlib
matplotlib.rc("font", family='Microsoft YaHei')

这两行代码将图片中的字体设置为了Microsoft YaHei,所以可以正常显示了

import matplotlib.pyplot as plt

import matplotlib
matplotlib.rc("font", family='Microsoft YaHei')
from numpy import square


squares = [1, 4, 9, 16, 25]
fig, ax = plt.subplots()
ax.plot(squares, linewidth = 3)

# 设置图表标题并给坐标轴加上标签。
ax.set_title("平方数", fontsize = 24)
ax.set_xlabel("值", fontsize = 14)
ax.set_ylabel("值的平方", fontsize = 14)

# 设置刻度标记的大小。
ax.tick_params(axis='both', labelsize =14 )


plt.show()

Python利用Matplotlib绘图无法显示中文字体的解决方案_开发语言_02

其他解决方案

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
# 黑体

使用模板(内置样式)后无法显示中文的解决方案

在模板代码后面加一行 plt.rcParams[‘font.sans-serif’] = ‘SimHei’

input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]

plt.style.use('seaborn')
plt.rcParams['font.sans-serif'] = 'SimHei'

fig, ax = plt.subplots()
ax.plot(input_values, squares, linewidth = 3)

Python利用Matplotlib绘图无法显示中文字体的解决方案_python_03

SimSun :宋体;KaiTI:楷体;Microsoft YaHei:微软雅黑
LiSu:隶书;FangSong:仿宋;Apple LiGothic Medium:苹果丽中黑;