matplotlib--基本用法

基本概念

我们需要预先导入一些库

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

Matplotlib在Figures(画布)上绘制数据,他们每个都可以包含一个或多个轴空间Axes,是一个可以在 x-y 坐标系中绘制点的区域(或者其他坐标系)。创建带有轴空间的 Figure 的最简单的方式就是使用 pyplot.subplots。然后我们可以使用 Axes.plot 来基于坐标轴绘制一些数据

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.

在这里插入图片描述

每一个Axes的绘图方法在matplotlib.pyplot模块中都有一个对应的函数,这个函数在“当前”坐标空间上完成绘制,如果当前没有坐标空间,便创建一个坐标空间及其所依附的图。上面的代码我们可以写得更简单一点

plt.plot([1, 2, 3, 4], [1, 4, 2, 3])

Figure的组成

一个Figure由以下部分组成

在这里插入图片描述

Figure

Figure 是整个图。Figure跟踪所有的轴空间(一个Figure可以包含多个轴空间)、一组“特殊”的艺术家(标题、图形图例、颜色条等),甚至嵌套的子图

创建一个Figure最简单的方式就是使用 pyplot

fig = plt.figure()  # an empty figure with no Axes
fig, ax = plt.subplots()  # a figure with a single Axes
fig, axs = plt.subplots(2, 2)  # a figure with a 2x2 grid of Axes

Axes

Axes 是轴空间,是带有数据空间的图像区域。一个给定的 Figure(图)可以包含多个轴空间,但是每个轴空间只能存在于一个图中。轴空间通常包含两个坐标轴Axis(在3D空间中包含三个坐标轴)。坐标轴为提供刻度和刻度标签来为轴空间Axis中的数据提供尺度。每个轴空间都包含一个 title(通过set_title()设置),一个x轴标签(通过set_xlabel()设置),一个y轴标签(通过set_ylabel()设置)。

Axes类及其成员函数是使用面向对象接口的最主要入口点。

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.
ax.set_title("first")
ax.set_xlabel("x")
ax.set_ylabel("y")

在这里插入图片描述

Axis

Axis 是轴,负责设定尺寸和数据范围,并且生成刻度和刻度标签。刻度的位置由Locator对象确定,刻度标签字符串由Formatter格式化。恰当的Locator/Formatter组合可以很好地控制刻度位置和标签。

Artist

Aritst 艺术家。本质上,在图上看到的所有东西都是artist(Figure, Axes, Axis对象也是)。当图渲染后,所有的aritists都被画在画布上。大部分Aritsts都被绑在Axes上;这样的一个Aritist不能被多个Axes共享,或从一个Axe移到另一个Axe。

绘图函数的输入数据

绘图函数希望数据是 numpy.array 或者 numpy.ma.masked_array 类型的,或者能够作为numpy.asarray 输入的对象。一些类似于数组的类,如pandas数据对象和numpy.matrix可能不会按预期工作,所以我们应该先将他们转成 numpy.array 类型。、

比如转换numpy.matrix类型的数据

b = np.matrix([[1, 2], [3, 4]])
b_asarray = np.asarray(b)

大多数方法也会分析可寻址的对象,比如字典,numpy.recarray 或 pandas.DataFrame.

Matplotlib允许您提供data关键字参数,通过传递x和y变量对应的字符串来绘图。(个人觉得并不重要)

np.random.seed(19680801)  # seed the random number generator.
data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

fig, ax = plt.subplots(figsize=(5, 2.7))
ax.scatter('a', 'b', c='c', s='d', data=data)
ax.set_xlabel('entry a')
ax.set_ylabel('entry b');

代码风格

如上所述,使用Matplotlib基本上有两种风格:

  • 显式创建图形与轴空间,并在其上调用方法的OO风格。

    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(figsize=(5, 2.7))
    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();  # 添加图例
    
  • 依靠pyplot自动创建和管理图形和轴,并使用pyplot函数进行绘图的plt风格。

    x = np.linspace(0, 2, 100)  # Sample data.
    
    plt.figure(figsize=(5, 2.7))
    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的更多介绍请关注后续内容

我们可以设置绘制的图像中Artist的格式,设置图像的标题等。详情

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长命百岁️

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值