Record: 3.pycharm, draw a picture, can not display Chinese

Try to use matplotlib for drawing, the code is as follows:

import matplotlib.pyplot as plt

# 创建了一个名为squares 的列表,在其中存储要用来制作图表的数据。
squares = [1, 4, 9, 16, 25]
# 调用函数subplots()
# 这个函数可在一张图片中绘制一个或多个图表。
# 变量fig 表示整张图片。变量ax 表示图片中的各个图表,大多数情况下要使用它。
fig , ax = plt.subplots()
# 调用方法plot(),尝试根据给定的数据以有意义的方式绘制图表。
ax.plot(squares , linewidth = 3)

# 设置图表标题并给坐标轴加上标签
# fontsize 指定图表中各种文字的大小
ax.set_title("平方数", fontsize = 24)
ax.set_xlabel("值", fontsize = 14)
ax.set_ylabel("值的平方", fontsize = 14)
# 设置刻度标记的大小
ax.tick_params(axis = 'both' , labelsize = 14)


plt.show()

The resulting picture can be displayed normally, but the Chinese in the picture cannot be displayed

And there are errors as follows:

D:\python_train\venv\Scripts\python.exe D:/python_train/mash/mpl_squares.py
D:\python\lib\tkinter\__init__.py:804: UserWarning: Glyph 20540 (\N{CJK UNIFIED IDEOGRAPH-503C}) missing from current font.
  func(*args)
D:\python\lib\tkinter\__init__.py:804: UserWarning: Glyph 30340 (\N{CJK UNIFIED IDEOGRAPH-7684}) missing from current font.
  func(*args)
D:\python\lib\tkinter\__init__.py:804: UserWarning: Glyph 24179 (\N{CJK UNIFIED IDEOGRAPH-5E73}) missing from current font.
  func(*args)
D:\python\lib\tkinter\__init__.py:804: UserWarning: Glyph 26041 (\N{CJK UNIFIED IDEOGRAPH-65B9}) missing from current font.
  func(*args)
D:\python\lib\tkinter\__init__.py:804: UserWarning: Glyph 25968 (\N{CJK UNIFIED IDEOGRAPH-6570}) missing from current font.
  func(*args)
D:\python\lib\tkinter\__init__.py:1883: UserWarning: Glyph 20540 (\N{CJK UNIFIED IDEOGRAPH-503C}) missing from current font.
  return self.func(*args)
D:\python\lib\tkinter\__init__.py:1883: UserWarning: Glyph 30340 (\N{CJK UNIFIED IDEOGRAPH-7684}) missing from current font.
  return self.func(*args)
D:\python\lib\tkinter\__init__.py:1883: UserWarning: Glyph 24179 (\N{CJK UNIFIED IDEOGRAPH-5E73}) missing from current font.
  return self.func(*args)
D:\python\lib\tkinter\__init__.py:1883: UserWarning: Glyph 26041 (\N{CJK UNIFIED IDEOGRAPH-65B9}) missing from current font.
  return self.func(*args)
D:\python\lib\tkinter\__init__.py:1883: UserWarning: Glyph 25968 (\N{CJK UNIFIED IDEOGRAPH-6570}) missing from current font.
  return self.func(*args)

After searching and studying, I found out that the reason is: Matplotlib does not support Chinese by default

Solution:

Before drawing, add the following code to the code:

# 在代码中添加如下语句 —— 设置字体为:SimHei(黑体)
plt.rcParams['font.sans-serif']=['SimHei'] 

Final result: no error reported

 

 

Guess you like

Origin blog.csdn.net/weixin_45314061/article/details/130014785