Matplotlib-快速上手-1

概述

推公式推累了,记录一下matplotlib这个库。

  1. Key Concepts:
  • 每个图就是一个Figure
  • 每个Figure里可以指定多个axes,然后在axes上plot_data,axes可以理解为坐标系
  • 每个axes有两个axis objects,axis可以理解为坐标轴
  • 后面的描述,Figure与图,axes与坐标系,axis与坐标轴混用
  1. 概念理解:
  • 可以创建多个图Figure,指定标题title、样式style等
  • 在一个Figure中,可以创建多个坐标系axes,axes拥有对坐标轴axis进行操作对象如限制axis的数据范围
  • 在一个axis中,拥有坐标的尺度scale或者刻度的数值ticks以及刻度的tickslabel

一、图的基本布局

1.1 图的构成

官方Matplotlib Tutorial贴一张图:
1
值得注意的点:

  • 图中最基础的对象称为Artist
  • 刻度tick有Major tick与Minor tick之分,其范围与label均可设置,tick依附于axis
  • 坐标轴axis主要的是范围与axis label
  • 此时有一个Figure,一个Axes还有要注意的图例Legend
import matplotlib.pyplot as plt
import numpy as np

1.2 图的两种创建方式

  • 准备随机数据
x1 = np.random.randn(10)
y1 = np.random.randn(10)

x2 = np.array([1.0, 3.0, 5.0])
y2 = np.array([4.0, 12.0, 20.0])

1.2.1 Axes创建方式(Object-Oriented Interface)

  • 默认创建一个figure,一个axes
fig, ax = plt.subplots() 
  • 默认创建一个figure,4个axes
fig, axs = plt.subplots(2,2) # ax是Axes对象,shape为(2,2)

此时一个图中有四个坐标系,在(0,0)与(1,1)这两个坐标系上plot_data

fig, axs = plt.subplots(2,2)
axs[0,0].plot(x1,y1)
axs[1,1].plot(x2,y2)
plt.show()

2

于是便可以利用Axes对象的Methods进行相关设置了,建议采用这种ax.method()的方式。(文末有完整代码)

1.2.2 Plt的创建方式(State-Based Interface)

plt.figure(1) # 创建id为1的图
plt.subplot(221) # 创建2行2列axes的布局layout,然后指定第一个axes
plt.plot(x1,y1)
plt.subplot(224) # 指定第四个axes
plt.plot(x2,y2)
plt.show()

3

1.3 小总结

  • axes的创建方式使用plt.subplots,然后根据坐标系进行plot,可以指定axes进行plot,然后后续调用axes.method()在axes上操作
  • plt的创建方式使用plt.figure以及plt.subplot进行图fig以及坐标系axes,然后后续调用plt.method()对current figure的current axes进行操作
  • 所以plt.method需要很清楚自己在哪个figure哪个axes上操作,还有切换axes,但ax.method则不用

为什么一个叫Object-Oriented,一个叫State-Based ,因为ax.method在操作的是Axes对象的方法,而plt.method在操作的是pyplot的函数调用,说明这些函数之间有一个公共的对象被其操作,因此底层需要记录公共对象的state

如果使用plt,怎么在上面的图补上空的坐标系?如下,大家可自行查看效果

plt.figure(1).add_subplot(222)

最后再强调一点:

  1. plt.method 是对current的对象进行操作,若figure与axes都有,则默认对current figure current axes进行操作
  2. plt.gcf(),plt.gca(),plt.xticks()都是默认获取当前figure,当前axes,当前figure当前axes的x刻度值的意思(gca = ‘get current axes’)
  3. 当明白plt与ax的区别后,有时混用也就很正常了,下一篇文章通过一些例子熟悉

二、Figure、Axes、Axis的基本设置

为了方便,采用single figure与single axes的方式

2.1 Figure对象

官方文档:https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure

记录一下常用的:

  • Figure添加标题:
fig = plt.figure()
fig.suptitle('Figure Tittle') # 添加Figure级别的Title
  • 对当前Figure的当前axes添加标题
plt.title("Scatterplot with line of best fit grouped by number of cylinders", fontsize=20)
  • 设置Figure的基本参数:
plt.figure(figsize=(16, 10), dpi= 80, facecolor='w', edgecolor='k')

2.2 Axes对象

官方文档:https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes

fig, ax = plt.subplots()
  • 设置坐标轴axis的label
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
  • 设置坐标轴axis的范围
ax.set_xlim([1,10])
ax.set_ylim([2,10])
ax.axis([1, 10, 2, 10]) # 同时设置x轴与y轴
  • 设置刻度tick的值以及标签
ax.set_xticks([lists of ticks])
ax.set_yticks([lists of ticks])
ax.set_xticklabels([lists of string labels])
ax.set_yticklabels([lists of string labels])
  • 设置图例legend与标题title
ax.set_title('axes title')
ax.set_label('legend_label') #设置图例标签
ax.legend() # 显示图例
  • 设置标注annotation以及文本text
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
             arrowprops=dict(facecolor='black', shrink=0.05))
ax.text(60, .025, r'$\mu=100,\ \sigma=15$')
ax.plot(x_data,y_data) # 默认是line
ax.scatter(_data,y_data) # 散点图
ax.hist(x_data) #直方图

三、 一个综合的例子

import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)
    
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

fig, axs = plt.subplots(1,2)  # (2,1)的axes布局
ax1, ax2 = axs[0], axs[1]
#################设置第一个axes################
# 设置标题
fig.suptitle('Figure Title')
ax1.set_title('Two plots')

# 设置axes的标签与范围
ax1.set_xlabel('t')
ax1.set_ylabel('f(t)')
ax1.set_xlim([0.0,4.0])
ax1.set_ylim([-0.75,1.0])

# 设置文本text以及标注annotate
ax1.text(2.5, -0.5, 'just for fun')
ax1.annotate(r'$\exp(-t) \ + \cos{2\pi t}$', xy=(0, 1.0), xytext=(1.0, 0.5),
             arrowprops=dict(facecolor='black', shrink=0.05))
             
# plot数据并设置legend的label
ax1.plot(t1, f(t1), 'bo', label = 'f(t1)') 
ax1.plot(t2, f(t2), 'k', label = 'f(t2)')

# 显示legend
ax1.legend()
#####################设置第二个axes#######################
ax2.set_title('One Plot')

ax2.scatter(t1, f(t1),label = 'f(t1)')
ax2.legend()
plt.show()

4

大家可以尝试一下用plt的state-based创建方式画出上图

第二篇会再介绍一些细节,比如figure的位置大小,每个axes的位置,怎么设置每个Artist的fontsize,color,style,legend size,linewidth等等细致化操作,以及怎么使用rcParams定制化Matplotlib,最后是封装Matplotlib的高级API库seaborn。

第三篇应该会开始学习一些Examples。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值