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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值