机器学习-数据科学库 02 matplotlib 折线图教程

matplotlib 简介

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
Matplotlib makes easy things easy and hard things possible.

matplotlib is a Matlab alternative

基本折线图

code:

# 导入库
from matplotlib import pyplot as plt 

# x、y 均为可迭代对象
x = range(2, 26, 2)
y = [15, 13, 14.5, 17, 20, 25, 26, 26, 24, 22, 18, 15]

# 绘制
plt.plot(x, y)
plt.show()

结果:

troubleshooting

如果 pycharm 遇到:

AttributeError: module 'backend_interagg' has no attribute 'FigureCanvas'

尝试去掉勾选如下配置:

参考:https://stackoverflow.com/questions/51214140/attributeerror-figurecanvasinteragg-object-has-no-attribute-renderer

调整画布

# 设置画布大小 dpi
plt.figure(figsize=(20, 8), dpi=80)

# 保存图片
plt.savefig("./sig_size.png")
plt.savefig("./sig_size.svg")

alt

调整坐标刻度

# 绘制要显示的坐标刻度
plt.xticks(range(2, 25))
plt.xticks([i/2 for i in range(4, 49)])

在这里插入图片描述

生成随机数据

x = range(0, 120)
y = [random.randint(20, 35) for i in range(120)]

在这里插入图片描述

坐标使用字符串数组 & 数据切片

# 按照 x 步长 slices
_x = list(x)

# y 轴用自定义模板字符串
_xticks_labels = ["10点{}分".format(i) for i in range(60)]
_xticks_labels += ["11点{}分".format(i) for i in range(60)]
plt.xticks(_x[::3], _xticks_labels[::3], rotation=90)

list(x) 才支持切片 参考 slices: https://stackoverflow.com/questions/9027862/what-does-listxy-do

在这里插入图片描述

支持中文编码

# 查看可用字体
fc-list 

# 查看中文字体
fc-list lang=zh

使用 matplotlib.rc(), 注意参考rc()源码:

# rc 属性配置
font = {'family': 'Heiti SC',
        'weight': 'bold',
        'size': 12}
matplotlib.rc('font', **font)

# 另外一种中文字体设置方式
my_font = font_manager.FontProperties(fname="/System/Library/Fonts/PingFang.ttc")

其他方案,参考:https://www.zhihu.com/question/25404709

from mplfonts import use_font

use_font('Noto Sans CJK SC')#指定中文字体

在这里插入图片描述

添加描述信息

# 添加描述信息
plt.xlabel("时间")
plt.ylabel("温度 单位(c)")
plt.title("10点到12点每分钟的气温变化情况")

绘制网格

plt.grid(alpha=0.4)

绘制多图 & 图例

# 多图
plt.plot(x,y_1,label="自己",color="#F08080")
plt.plot(x,y_2,label="同桌",color="#DB7093",linestyle="--")

# 图例
plt.legend(prop=my_font,loc="upper left")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值