matplotlib第1部分 认识matplotlib

Matplotlib 回顾

认识 matplotlib

Matplotlib 是一个 python 2D 绘图库,用来绘制各种静态,动态,交互式的图表。已成为 python 中公认的数据可视化工具。

绘图小案例

matplotlib 的图像是画在 figure 上的,每一个 figure 又包含了一个或多个 axes (一个可以指定坐标系的子区域)。最简单的创建 figure 以及 axes 的方式是通过 pyplot.subplots 命令,创建 axes 之后,可以使用 Axes.plot 绘制最简单的折线图。

# 导入库
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
fig,ax=plt.subplots() #创建一个包含一个axes的figure
ax.plot([1,2,3,4],[1,4,2,3]); # 绘制图像

结果如下
在这里插入图片描述
注意:在 jupyter notebook 中使用 matplotlib 时会发现,代码运行后会自动打印下面的一段话
在这里插入图片描述
处理方法有三个:

  1. 在代码块最后加一个分号;
  2. 在代码块最后加一句 plt.show();
  3. 在绘图时将绘图对象显式赋值给一个变量,如将 plt.plot([1,2,3,4]) 改成 line=plt.plot([1,2,3,4])

Figure 的组成

Figure顶层级,用来容纳所有绘图元素
Axesmatplotlib宇宙的核心,容纳了大量元素用来构造一幅幅子图,一个figure可以由一个或多个子图组成
Axisaxes的下属层级,用于处理所有和坐标轴,网格有关的元素
Tickaxis的下属层级,用来处理所有和刻度有关的元素

在这里插入图片描述

两种绘图接口

1. 显式创建 figure 和 axes

下面展示一些 内联代码片

x=np.linspace(0,4,50)
fig,ax=plt.subplots()
ax.plot(x,x,label='linear')
ax.plot(x,x**2,label='quadratic')
ax.plot(x,x**3,label='cubic')
ax.set_xlabel('x label') #设置x轴坐标标题
ax.set_ylabel('y label') #设置y轴坐标标题
ax.set_title('Simple Plot') #设置标题
ax.legend() #显示图例
plt.show() #显示图

结果如下:
在这里插入图片描述

2. 依赖 pyplot 自动创建 figure 和 axes

x=np.linspace(0,8,50)
plt.plot(x,x,label='linear')
plt.plot(x,x**2,label='quadratic')
plt.plot(x,x**3,label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title('Simple Plot')
plt.legend()
plt.show()

结果如下
在这里插入图片描述

通用绘图模板

1. 以 OO模式(object-oriented style)

# step1 准备数据
x=np.linspace(0,2,100)
y=x**2
# step2 设置绘图样式
mpl.rc('lines',linewidth=4,linestyle='-.')
# step3 定义布局
fig,ax=plt.subplots()
# step4 绘制图像
ax.plot(x,y,label='linear')
# step5 添加标签
ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_title('Simple Plot')
ax.legend();

结果如下:
在这里插入图片描述

2. 以 pyplot 绘图模式

# step1 准备数据
x=np.linspace(0,2,100)
y=x**2
# step2 绘制图像
plt.plot(x,y,label='linear',linestyle=':',color='r')
# step3 添加标签
plt.xlabel('x label')
plt.ylabel('y label')
plt.title('Simple Plot')
plt.legend()
plt.show()

结果如下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值