栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

matplotlib从折线图入门并解决中文乱码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

matplotlib从折线图入门并解决中文乱码

matplotlib从折线图入门并解决中文乱码
  • 1. 第一个折线图
  • 2. 中文乱码
  • 3. 中文乱码解决方法
    • 3.1 方法一:调用系统文字
    • 3.2 方法二:使用自定义文字

【安装后查看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()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/916249.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号