matplotlib从折线图入门并解决中文乱码
【安装后查看matplotlib版本】
# 查看版本
import matplotlib
print(matplotlib.__version__)
1. 第一个折线图
from matplotlib import pyplot as plt
# x, y值数据
x = [1, 4, 8, 12]
y = [1, 3, 6, 9]
# 定义标题与标签
plt.title("TEST")
plt.xlabel("x")
plt.ylabel("y")
# 绘图
plt.plot(x,y)
plt.show()
结果:
2. 中文乱码
backend_interagg.py:65: UserWarning: Glyph 36724 (\N{CJK UNIFIED IDEOGRAPH-8F74}) missing from current font. FigureCanvasAgg.draw(self)
3. 中文乱码解决方法
3.1 方法一:调用系统文字
# 查看字体
a=sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
for i in a:
print(i)
# 选择字体
# plt.rcParams['font.family']=['STFangsong']
plt.rcParams['font.family']=['Microsoft YaHei']
Arial
Bahnschrift
...
Microsoft YaHei
...
Wingdings 3
YouYuan
修改后:
from matplotlib import pyplot as plt
# 选择字体
plt.rcParams['font.family'] = ['Microsoft YaHei']
# x, y值数据
x = [1, 4, 8, 12]
y = [1, 3, 6, 9]
# 定义标题与标签
plt.title("TEST")
plt.xlabel("x轴")
plt.ylabel("y轴")
# 绘图
plt.plot(x, y)
plt.show()
3.2 方法二:使用自定义文字
【字体SourceHanSansSC-Bold.otf】原网站:【菜鸟教程】
将字体和.py文件放在同一目录下
执行:
from matplotlib import pyplot as plt
# 自定义字体
zh_font = matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")
# x, y值数据
x = [1, 4, 8, 12]
y = [1, 3, 6, 9]
# 定义标题与标签
plt.title("TEST")
plt.xlabel("x轴", fontproperties=zh_font)
plt.ylabel("y轴", fontproperties=zh_font)
# 绘图
plt.plot(x, y)
plt.show()