尝试使用matplotlib进行画图,代码如下:

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()

结果图片可以正常显示,但是图中的中文却不能显示出来

并有报错如下:

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)

经查找学习,找出原因是: Matplotlib 默认情况不支持中文

解决方法:

在绘图前,对代码中添加如下代码:

# 在代码中添加如下语句 —— 设置字体为:SimHei(黑体)

plt.rcParams['font.sans-serif']=['SimHei']

最终结果:未报错

 

 

相关链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: