初识Matplotlib(一)
一、简介
Matplotlib 是 Python 的绘图库,它能让使用者很轻松地将数据图形化,并且提供多样化的输出格式。
Matplotlib 可以用来绘制各种静态,动态,交互式的图表。
Matplotlib 是一个非常强大的 Python 画图工具,我们可以使用该工具将很多数据通过图表的形式更直观的呈现出来。
Matplotlib 可以绘制线图、散点图、等高线图、条形图、柱状图、3D 图形、甚至是图形动画等等。
二、一个简单的例子
Matplotlib的图像是画在figure(如windows,jupyter窗体)上的,每一个figure又包含了一个或多个axes(一个可以指定坐标系的子区域)。最简单的创建figure以及axes的方式是通过pyplot.subplots命令,创建axes以后,可以使用Axes.plot绘制最简易的折线图。
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots() # Create a figure containing a single axes.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]); # Plot some data on the axes.
plt.show() # show picture
你还可以通过一种更简单的方式绘制图像,matplotlib.pyplot方法能够直接在当前axes上绘制图像,如果用户未指定axes,matplotlib会帮你自动创建一个。所以上面的例子也可以简化为以下这一行代码。
line =plt.plot([1, 2, 3, 4], [1, 4, 2, 3]) # 替换 plt.subplots()与ax.plot()
三、Figure的组成
现在我们来深入看一下figure的组成。通过一张figure解剖图,我们可以看到一个完整的matplotlib图像通常会包括以下四个层级,这些层级也被称为容器(container)。
在matplotlib的世界中,我们将通过各种命令方法来操纵图像中的每一个部分,从而达到数据可视化的最终效果,一副完整的图像实际上是各类子元素的集合。
Figure:顶层级,用来容纳所有绘图元素Axes:matplotlib宇宙的核心,容纳了大量元素用来构造一幅幅子图,一个figure可以由一个或多个子图组成Axis:axes的下属层级,用于处理所有和坐标轴,网格有关的元素Tick:axis的下属层级,用来处理所有和刻度有关的元素
四、两种绘图接口
matplotlib提供了两种最常用的绘图接口
- 显式创建figure和axes,在上面调用绘图方法,也被称为OO模式(object-oriented style)
- 依赖pyplot自动创建figure和axes,并绘图
使用第一种绘图接口,是这样的:
x = np.linspace(0, 2, 100) # Sample data.
# Note that even in the OO-style, we use `.pyplot.figure` to create the Figure.
fig, ax = plt.subplots()
ax.plot(x, x, label='linear') # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic') # Plot more data on the axes...
ax.plot(x, x**3, label='cubic') # ... and some more.
ax.set_xlabel('x label') # Add an x-label to the axes.
ax.set_ylabel('y label') # Add a y-label to the axes.
ax.set_title("Simple Plot") # Add a title to the axes.
ax.legend(); # Add a legend.
或 pyplot 风格:
x = np.linspace(0, 2, 100) # Sample data.
plt.figure()
plt.plot(x, x, label='linear') # Plot some data on the (implicit) axes.
plt.plot(x, x**2, label='quadratic') # etc.
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend();
一般来说,建议使用 OO 风格,特别是对于复杂的绘图,以及旨在作为更大项目的一部分重复使用的函数和脚本。但是,pyplot 样式对于快速交互工作来说非常方便。
五、通用绘图模板
由于matplotlib的知识点非常繁杂,在实际使用过程中也不可能将全部API都记住,很多时候都是边用边查。因此这里提供一个通用的绘图基础模板,任何复杂的图表几乎都可以基于这个模板骨架填充内容而成。初学者刚开始学习时只需要牢记这一模板就足以应对大部分简单图表的绘制,在学习过程中可以将这个模板模块化,了解每个模块在做什么,在绘制复杂图表时如何修改,填充对应的模块。
# 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() ;
接下来就按照通用绘图模板中的步骤逐一说明每一个模块。


浙公网安备 33010602011771号