Matplotlib 简明教程

Matplotlib - Quick Guide

Matplotlib - Introduction

Matplotlib 是用于数据可视化的最流行的 Python 包之一。它是一个跨平台库,用于根据数组中的数据进行 2D 绘图。Matplotlib 用 Python 编写,并使用 NumPy,即 Python 的数值数学扩展。它提供了一个面向对象 API,有助于使用 Python GUI 工具包(如 PyQt、WxPython 和 Tkinter)将绘图嵌入到应用程序中。它还可以用于 Python 和 IPython shell、Jupyter notebook 和 Web 应用程序服务器。

Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. Matplotlib is written in Python and makes use of NumPy, the numerical mathematics extension of Python. It provides an object-oriented API that helps in embedding plots in applications using Python GUI toolkits such as PyQt, WxPythonotTkinter. It can be used in Python and IPython shells, Jupyter notebook and web application servers also.

Matplotlib 有一个名为 Pylab 的过程接口,其设计是模仿 MATLAB(一种由 MathWorks 开发的专有编程语言)。Matplotlib 结合 NumPy 可以被视为 MATLAB 的开源等效项。

Matplotlib has a procedural interface named the Pylab, which is designed to resemble MATLAB, a proprietary programming language developed by MathWorks. Matplotlib along with NumPy can be considered as the open source equivalent of MATLAB.

Matplotlib 最初由 John D. Hunter 于 2003 年编写。当前稳定版本是 2018 年 1 月发布的 2.2.0 版本。

Matplotlib was originally written by John D. Hunter in 2003. The current stable version is 2.2.0 released in January 2018.

Matplotlib - Environment Setup

Matplotlib 及其依赖包在标准 Python 包存储库中以 wheels 包的形式提供,并且可以使用 pip 包管理器在 Windows、Linux 以及 MacOS 系统中进行安装。

Matplotlib and its dependency packages are available in the form of wheel packages on the standard Python package repositories and can be installed on Windows, Linux as well as MacOS systems using the pip package manager.

pip3 install matplotlib

如果所有用户都未安装 Python 2.7 或 3.4 版本,则需要安装 Microsoft Visual C 2008(64 位或 32 位(用于 Python 2.7))或 Microsoft Visual C 2010(64 位或 32 位(用于 Python 3.4))可再发行包。

Incase Python 2.7 or 3.4 versions are not installed for all users, the Microsoft Visual C 2008 (64 bit or 32 bit forPython 2.7) or Microsoft Visual C 2010 (64 bit or 32 bit for Python 3.4) redistributable packages need to be installed.

如果你在 Mac 上使用 Python 2.7,请执行以下命令 −

If you are using Python 2.7 on a Mac, execute the following command −

xcode-select –install

执行上述命令时,可能会编译一个依赖项 subprocess32。

Upon execution of the above command, the subprocess32 - a dependency, may be compiled.

对于非常古老的 Linux 和 Python 2.7 版本,你可能需要安装 subprocess32 的主版本。

On extremely old versions of Linux and Python 2.7, you may need to install the master version of subprocess32.

Matplotlib 要求大量依赖项 −

Matplotlib requires a large number of dependencies −

  1. Python (>= 2.7 or >= 3.4)

  2. NumPy

  3. setuptools

  4. dateutil

  5. pyparsing

  6. libpng

  7. pytz

  8. FreeType

  9. cycler

  10. six

或者,你还可以安装多个程序包以启用更好的用户界面工具包。

Optionally, you can also install a number of packages to enable better user interface toolkits.

  1. tk

  2. PyQt4

  3. PyQt5

  4. pygtk

  5. wxpython

  6. pycairo

  7. Tornado

为了更好地支持动画输出格式和图像文件格式,LaTeX 等,你可以安装下列内容 −

For better support of animation output format and image file formats, LaTeX, etc., you can install the following −

  1. _mpeg/avconv

  2. ImageMagick

  3. Pillow (>=2.0)

  4. LaTeX and GhostScript (for rendering text with LaTeX).

  5. LaTeX and GhostScript (for rendering text with LaTeX).

Matplotlib - Anaconda distribution

Anaconda 是针对数据处理、预测性分析和科学计算而设计的 Python 和 R 编程语言的免费开源发行版。该发行版使包管理和部署变得非常简单轻松。Matplotlib 和许多其他有用的(数据)科学工具构成了该发行版的一部分。包版本由包管理系统 Conda 进行管理。Anaconda 的优点是可以使用 Anaconda 的 Conda(一个包、依赖和环境管理器)轻松安装超过 720 个包。

Anaconda is a free and open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing. The distribution makes package management and deployment simple and easy. Matplotlib and lots of other useful (data) science tools form part of the distribution. Package versions are managed by the package management system Conda. The advantage of Anaconda is that you have access to over 720 packages that can easily be installed with Anaconda’s Conda, a package, dependency, and environment manager.

可以在 https://www.anaconda.com/download/. 处下载 Anaconda 发行版以进行安装。对于在 Windows 中进行安装,有 32 位和 64 位二进制文件可用−

Anaconda distribution is available for installation at https://www.anaconda.com/download/. For installation on Windows, 32 and 64 bit binaries are available −

安装是一个非常简单的基于向导的过程。可以选择将 Anaconda 添加至 PATH 变量或将 Anaconda 注册为默认 Python。

Installation is a fairly straightforward wizard based process. You can choose between adding Anaconda in PATH variable and registering Anaconda as your default Python.

对于在 Linux 中进行安装,请从下载页面下载 32 位和 64 位安装程序 −

For installation on Linux, download installers for 32 bit and 64 bit installers from the downloads page −

现在,从 Linux 终端运行以下命令 −

Now, run the following command from the Linux terminal −

$ bash Anaconda3-5.0.1-Linux-x86_64.sh

Canopy 和 ActiveState 是 Windows、macOS 和 Linux 常用平台的最佳选择。Windows 用户可以在 WinPython 中找到一项选项。

Canopy and ActiveState are the most sought after choices for Windows, macOS and common Linux platforms. The Windows users can find an option in WinPython.

Matplotlib - Jupyter Notebook

Jupyter 是一个宽松的缩写,表示 Julia、Python 和 R。这些编程语言是 Jupyter 应用程序最初的目标语言,但如今该 Jupyter 技术还支持其他许多语言。

Jupyter is a loose acronym meaning Julia, Python, and R. These programming languages were the first target languages of the Jupyter application, but nowadays, the notebook technology also supports many other languages.

2001 年,费尔南多·佩雷斯开始开发 IPython。 IPython 是一个用于在多种编程语言中进行交互计算的命令外壳,最初是为 Python 开发的。

In 2001, Fernando Pérez started developing Ipython. IPython is a command shell for interactive computing in multiple programming languages, originally developed for the Python.

考虑 IPython 提供的以下功能−

Consider the following features provided by IPython −

  1. Interactive shells (terminal and Qt-based).

  2. A browser-based notebook with support for code, text, mathematical expressions, inline plots and other media.

  3. Support for interactive data visualization and use of GUI toolkits.

  4. Flexible, embeddable interpreters to load into one’s own projects.

2014 年,Fernando Pérez 宣布了 IPython 的一个衍生项目,名为 Project Jupyter。IPython 将继续作为 Python shell 和 Jupyter 的内核存在,而笔记本和其他与语言无关的 IPython 部分将移至 Jupyter 名称下。Jupyter 为 Julia、R、Haskell 和 Ruby 添加了支持。

In 2014, Fernando Pérez announced a spin-off project from IPython called Project Jupyter. IPython will continue to exist as a Python shell and a kernel for Jupyter, while the notebook and other language-agnostic parts of IPython will move under the Jupyter name. Jupyter added support for Julia, R, Haskell and Ruby.

要启动 Jupyter notebook,请打开 Anaconda navigator(Anaconda 中包含的一个桌面图形用户界面,允许你在不用命令行命令的情况下启动应用程序和轻松管理 Conda 包、环境和通道)。

To start the Jupyter notebook, open Anaconda navigator (a desktop graphical user interface included in Anaconda that allows you to launch applications and easily manage Conda packages, environments and channels without the need to use command line commands).

anaconda navigator

Navigator 显示发行版中已安装的组件。

Navigator displays the installed components in the distribution.

anaconda navigator root

从 Navigator 启动 Jupyter Notebook −

Launch Jupyter Notebook from the Navigator −

jupyter notebook

你将在以下地址的 Web 浏览器中看到打开的应用程序 - http://localhost:8888.

You will see the application opening in the web browser on the following address − http://localhost:8888.

command prompt

你可能首先需要制作一个新笔记本。你可以轻松地单击“文件”选项卡中的“新建按钮”来做到这一点。你会看到,你可以选择制作常规文本文件、文件夹和终端。最后,你还会看到制作 Python 3 笔记本的选项。

You probably want to start by making a new notebook. You can easily do this by clicking on the "New button" in the "Files tab". You see that you have the option to make a regular text file, a folder, and a terminal. Lastly, you will also see the option to make a Python 3 notebook.

python 3 notebook

Matplotlib - Pyplot API

带有 *.ipynb*扩展名的无标题新笔记本(代表 IPython 笔记本)显示在浏览器的新的选项卡中。

A new untitled notebook with the *.ipynb*extension (stands for the IPython notebook) is displayed in the new tab of the browser.

pyplot api

matplotlib.pyplot 是一系列命令式函数,让 Matplotlib 能够像 MATLAB 一样工作。每个 Pyplot 函数都会对图形进行一些更改。例如,一个函数创建图形、图形中的绘图区域、在绘图区域中绘制一些线条、用标签装饰图形等。

matplotlib.pyplot is a collection of command style functions that make Matplotlib work like MATLAB. Each Pyplot function makes some change to a figure. For example, a function creates a figure, a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.

Types of Plots

Sr.No

Function & Description

1

Bar Make a bar plot.

2

Barh Make a horizontal bar plot.

3

Boxplot Make a box and whisker plot.

4

Hist Plot a histogram.

5

hist2d Make a 2D histogram plot.

6

Pie Plot a pie chart.

7

Plot Plot lines and/or markers to the Axes.

8

Polar Make a polar plot..

9

Scatter Make a scatter plot of x vs y.

10

Stackplot Draws a stacked area plot.

11

Stem Create a stem plot.

12

Step Make a step plot.

13

Quiver Plot a 2-D field of arrows.

Image Functions

Sr.No

Function & Description

1

Imread Read an image from a file into an array.

2

Imsave Save an array as in image file.

3

Imshow Display an image on the axes.

Axis Functions

Sr.No

Function & Description

1

Axes Add axes to the figure.

2

Text Add text to the axes.

3

Title Set a title of the current axes.

4

Xlabel Set the x axis label of the current axis.

5

Xlim Get or set the x limits of the current axes.

6

Xscale .

7

Xticks Get or set the x-limits of the current tick locations and labels.

8

Ylabel Set the y axis label of the current axis.

9

Ylim Get or set the y-limits of the current axes.

10

Yscale Set the scaling of the y-axis.

11

Yticks Get or set the y-limits of the current tick locations and labels.

Figure Functions

Sr.No

Function & Description

1

Figtext Add text to figure.

2

Figure Creates a new figure.

3

Show Display a figure.

4

Savefig Save the current figure.

5

Close Close a figure window.

Matplotlib - Simple Plot

在本章中,我们将学习如何使用 Matplotlib 创建一个简单的绘图。

In this chapter, we will learn how to create a simple plot with Matplotlib.

我们现在将使用 Matplotlib 显示一个简单的弧度角对正弦值的折线图。首先,按照惯例,使用别名 plt 导入 Matplotlib 包中的 Pyplot 模块。

We shall now display a simple line plot of angle in radians vs. its sine value in Matplotlib. To begin with, the Pyplot module from Matplotlib package is imported, with an alias plt as a matter of convention.

import matplotlib.pyplot as plt

接下来,我们需要一个要绘制的数字数组。可以在使用 np 别名导入的 NumPy 库中定义各种数组函数。

Next we need an array of numbers to plot. Various array functions are defined in the NumPy library which is imported with the np alias.

import numpy as np

我们现在使用 NumPy 库的 arange() 函数获取 0 到 2π 之间的角度的 ndarray 对象。

We now obtain the ndarray object of angles between 0 and 2π using the arange() function from the NumPy library.

x = np.arange(0, math.pi*2, 0.05)

ndarray 对象用作图形的 x 轴上的值。通过以下语句获取要在 y 轴上显示的对应的 x 角度的正弦值:

The ndarray object serves as values on x axis of the graph. The corresponding sine values of angles in x to be displayed on y axis are obtained by the following statement −

y = np.sin(x)

使用 plot() 函数绘制来自两个数组的值。

The values from two arrays are plotted using the plot() function.

plt.plot(x,y)

您可以设置绘图标题以及 x 和 y 轴的标签。

You can set the plot title, and labels for x and y axes.

You can set the plot title, and labels for x and y axes.
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')

Plot 查看器窗口由 show() 函数调用:

The Plot viewer window is invoked by the show() function −

plt.show()

完整程序如下 −

The complete program is as follows −

from matplotlib import pyplot as plt
import numpy as np
import math #needed for definition of pi
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
plt.plot(x,y)
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
plt.show()

当执行上述代码行时,将显示以下图形:

When the above line of code is executed, the following graph is displayed −

simple plot

现在,将 Jupyter 笔记本与 Matplotlib 一起使用。

Now, use the Jupyter notebook with Matplotlib.

如前所述,从 Anaconda navigator 或命令行启动 Jupyter notebook。在输入单元格中,输入 Pyplot 和 NumPy 的导入语句−

Launch the Jupyter notebook from Anaconda navigator or command line as described earlier. In the input cell, enter import statements for Pyplot and NumPy −

from matplotlib import pyplot as plt
import numpy as np

要在 notebook 本身中显示绘图输出(而不是在单独查看器中显示),输入以下魔法语句−

To display plot outputs inside the notebook itself (and not in the separate viewer), enter the following magic statement −

%matplotlib inline

获取 x 为包含 0 到 2π 之间弧度的 ndarray 对象,并获取 y 为每个角度的正弦值−

Obtain x as the ndarray object containing angles in radians between 0 to 2π, and y as sine value of each angle −

import math
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)

设置 x 和 y 轴的标签以及绘图标题−

Set labels for x and y axes as well as the plot title −

plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')

最后执行 plot() 函数在 notebook 中生成正弦波显示(无需运行 show() 函数)−

Finally execute the plot() function to generate the sine wave display in the notebook (no need to run the show() function) −

plt.plot(x,y)

执行代码的最后一行后,将显示以下输出−

After the execution of the final line of code, the following output is displayed −

final line of code

Matplotlib - PyLab module

PyLab 是面向 Matplotlib 面向对象绘图库的过程化界面。Matplotlib 是整个包;matplotlib.pyplot 是 Matplotlib 中的一个模块;PyLab 与 Matplotlib 一起安装的一个模块。

PyLab is a procedural interface to the Matplotlib object-oriented plotting library. Matplotlib is the whole package; matplotlib.pyplot is a module in Matplotlib; and PyLab is a module that gets installed alongside Matplotlib.

PyLab 是一个方便的模块,它以单个名称空间大量导入 matplotlib.pyplot(用于绘图)和 NumPy(用于数学和处理数组)。尽管许多示例使用 PyLab,但不再建议使用。

PyLab is a convenience module that bulk imports matplotlib.pyplot (for plotting) and NumPy (for Mathematics and working with arrays) in a single name space. Although many examples use PyLab, it is no longer recommended.

Basic Plotting

可以使用 plot 命令对曲线进行绘制。它采用一对等长数组(或序列)-

Plotting curves is done with the plot command. It takes a pair of same-length arrays (or sequences) −

from numpy import *
from pylab import *
x = linspace(-3, 3, 30)
y = x**2
plot(x, y)
show()

上述代码行生成以下输出 -

The above line of code generates the following output −

basic plotting

要绘制符号而非线条,请提供一个附加的字符串参数。

To plot symbols rather than lines, provide an additional string argument.

symbols

- , –, -., , . , , , o , ^ , v , < , > , s , + , x , D , d , 1 , 2 , 3 , 4 , h , H , p ,

, _

现在,考虑执行以下代码 -

Now, consider executing the following code −

from pylab import *
x = linspace(-3, 3, 30)
y = x**2
plot(x, y, 'r.')
show()

它以红色圆点形式显示图,如下所示-

It plots the red dots as shown below −

additional string argument

可以叠加绘图。只需使用多个绘图命令。使用 clf() 清除绘图。

Plots can be overlaid. Just use the multiple plot commands. Use clf() to clear the plot.

from pylab import *
plot(x, sin(x))
plot(x, cos(x), 'r-')
plot(x, -sin(x), 'g--')
show()

上述代码行生成以下输出 -

The above line of code generates the following output −

multiple plot commands

Matplotlib - Object-oriented Interface

虽然可以快速使用 matplotlib.pyplot 模块生成绘图,但建议使用面向对象的方法,因为它可以更多地控制和自定义绘图。大多数函数也在 matplotlib.axes.Axes 类中提供。

While it is easy to quickly generate plots with the matplotlib.pyplot module, the use of object-oriented approach is recommended as it gives more control and customization of your plots. Most of the functions are also available in the matplotlib.axes.Axes class.

使用更正式的面向对象方法的主要思想是创建图对象,然后只需调出该对象的方法或属性。此方法有助于更好地处理其上有多个绘图的画布。

The main idea behind using the more formal object-oriented method is to create figure objects and then just call methods or attributes off of that object. This approach helps better in dealing with a canvas that has multiple plots on it.

在面向对象接口中,Pyplot 仅用于一些函数,例如图形创建,并且用户显式创建图形和轴对象并对其进行跟踪。在此级别,用户使用 Pyplot 创建图形,并且可以通过这些图形创建一或多个轴对象。然后,这些轴对象用于大多数绘图操作。

In object-oriented interface, Pyplot is used only for a few functions such as figure creation, and the user explicitly creates and keeps track of the figure and axes objects. At this level, the user uses Pyplot to create figures, and through those figures, one or more axes objects can be created. These axes objects are then used for most plotting actions.

首先,我们创建一个 figure 实例,该实例提供一个空画布。

To begin with, we create a figure instance which provides an empty canvas.

fig = plt.figure()

现在将轴添加到图形中。 add_axes() 方法需要一个包含 4 个元素的列表对象,这些元素分别对应于图形的左、下、宽和高。每个数字必须介于 0 和 1 之间−

Now add axes to figure. The add_axes() method requires a list object of 4 elements corresponding to left, bottom, width and height of the figure. Each number must be between 0 and 1 −

ax=fig.add_axes([0,0,1,1])

设置 x 和 y 轴的标签以及标题−

Set labels for x and y axis as well as title −

ax.set_title("sine wave")
ax.set_xlabel('angle')
ax.set_ylabel('sine')

调用轴对象的 plot() 方法。

Invoke the plot() method of the axes object.

ax.plot(x,y)

如果你正在使用 Jupyter notebook,则必须发出 %matplotlib inline 指令;pyplot 模块的 otherwistshow() 函数将显示绘图。

If you are using Jupyter notebook, the %matplotlib inline directive has to be issued; the otherwistshow() function of pyplot module displays the plot.

考虑执行以下代码−

Consider executing the following code −

from matplotlib import pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.set_title("sine wave")
ax.set_xlabel('angle')
ax.set_ylabel('sine')
plt.show()

Output

上述代码行生成以下输出 -

The above line of code generates the following output −

add axes method

当在 Jupyter notebook 中运行时,相同的代码会显示如下所示的输出−

The same code when run in Jupyter notebook shows the output as shown below −

jupyter notebook output

Matplotlib - Figure Class

matplotlib.figure 模块包含 Figure 类。它是所有绘图元素的顶级容器。通过从 pyplot 模块调用 figure() 函数来实例化 Figure 对象−

The matplotlib.figure module contains the Figure class. It is a top-level container for all plot elements. The Figure object is instantiated by calling the figure() function from the pyplot module −

fig = plt.figure()

下表显示了附加参数−

The following table shows the additional parameters −

Figsize

(width,height) tuple in inches

Dpi

Dots per inches

Facecolor

Figure patch facecolor

Edgecolor

Figure patch edge color

Linewidth

Edge line width

Matplotlib - Axes Class

轴对象是带有数据空间的图像区域。给定的图形可以包含多个轴对象,但给定的轴对象只能在一个图形中。轴对象包含两个(或 3D 情况下的三个)轴对象。轴类及其成员函数是使用 OO 接口的主要入口。

Axes object is the region of the image with the data space. A given figure can contain many Axes, but a given Axes object can only be in one Figure. The Axes contains two (or three in the case of 3D) Axis objects. The Axes class and its member functions are the primary entry point to working with the OO interface.

通过调用add_axes()方法,将Axes对象添加到图形。它返回Axes对象,并以rect [left, bottom, width, height]位置添加一个Axes,其中所有数量都是以图形宽度和高度的几分之一表示的。

Axes object is added to figure by calling the add_axes() method. It returns the axes object and adds an axes at position rect [left, bottom, width, height] where all quantities are in fractions of figure width and height.

Parameter

以下是Axes类的参数:

Following is the parameter for the Axes class −

  1. rect − A 4-length sequence of [left, bottom, width, height] quantities.

ax=fig.add_axes([0,0,1,1])

Axes类的以下成员函数向绘图中添加了不同的元素:

The following member functions of axes class add different elements to plot −

Legend

Axes类的 legend() 方法向绘图中添加一个图例。它需要三个参数:

The legend() method of axes class adds a legend to the plot figure. It takes three parameters −

ax.legend(handles, labels, loc)

其中labels是字符串序列并且处理Line2D或Patch实例的序列。loc可以是指定图例位置的字符串或整数。

Where labels is a sequence of strings and handles a sequence of Line2D or Patch instances. loc can be a string or an integer specifying the legend location.

Location string

Location code

Best

0

upper right

1

upper left

2

lower left

3

lower right

4

Right

5

Center left

6

Center right

7

lower center

8

upper center

9

Center

10

axes.plot()

这是Axes类的基本方法,它将一个数组的值作为线条或标记绘制在另一个数组上。plot()方法可以有一个可选的格式字符串参数来指定线条和标记的颜色、样式和大小。

This is the basic method of axes class that plots values of one array versus another as lines or markers. The plot() method can have an optional format string argument to specify color, style and size of line and marker.

Color codes

Character

Color

‘b’

Blue

‘g’

Green

‘r’

Red

‘b’

Blue

‘c’

Cyan

‘m’

Magenta

‘y’

Yellow

‘k’

Black

‘b’

Blue

‘w’

White

Marker codes

Character

Description

‘.’

Point marker

‘o’

Circle marker

‘x’

X marker

‘D’

Diamond marker

‘H’

Hexagon marker

‘s’

Square marker

‘+’

Plus marker

Line styles

Character

Description

‘-‘

Solid line

‘—‘

Dashed line

‘-.’

Dash-dot line

‘:’

Dotted line

‘H’

Hexagon marker

以下示例以折线图的形式显示了电视和智能手机的广告费用和销售数据。表示电视的线是实线,黄色,有方块标记,而智能手机线是虚线,绿色,有圆形标记。

Following example shows the advertisement expenses and sales figures of TV and smartphone in the form of line plots. Line representing TV is a solid line with yellow colour and square markers whereas smartphone line is a dashed line with green colour and circle marker.

import matplotlib.pyplot as plt
y = [1, 4, 9, 16, 25,36,49, 64]
x1 = [1, 16, 30, 42,55, 68, 77,88]
x2 = [1,6,12,18,28, 40, 52, 65]
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
l1 = ax.plot(x1,y,'ys-') # solid line with yellow colour and square marker
l2 = ax.plot(x2,y,'go--') # dash line with green colour and circle marker
ax.legend(labels = ('tv', 'Smartphone'), loc = 'lower right') # legend placed at lower right
ax.set_title("Advertisement effect on sales")
ax.set_xlabel('medium')
ax.set_ylabel('sales')
plt.show()

当执行上述代码行时,它产生以下绘图:

When the above line of code is executed, it produces the following plot −

advertisement effect

Matplotlib - Multiplots

在本章中,我们将学习如何在同一画布上创建多个子图。

In this chapter, we will learn how to create multiple subplots on same canvas.

subplot() 函数返回给定网格位置处的Axes对象。此函数的调用签名为:

The subplot() function returns the axes object at a given grid position. The Call signature of this function is −

plt.subplot(subplot(nrows, ncols, index)

在当前图形中,该函数创建一个Axes对象,并将其返回到nrows by ncolsaxes网格的位置索引处。索引从1到nrows * ncols,以行优先顺序递增。如果nrows、ncols和index均小于10。索引也可以表示为单个、连接的、三位数字。

In the current figure, the function creates and returns an Axes object, at position index of a grid of nrows by ncolsaxes. Indexes go from 1 to nrows * ncols, incrementing in row-major order.Ifnrows, ncols and index are all less than 10. The indexes can also be given as single, concatenated, threedigitnumber.

例如,subplot(2, 3, 3)和subplot(233)都在当前图形的右上角创建一个Axes,占据图形高度的一半和图形宽度的三分之一。

For example, subplot(2, 3, 3) and subplot(233) both create an Axes at the top right corner of the current figure, occupying half of the figure height and a third of the figure width.

创建子图将删除其与超出共享边界的任何预先存在的子图重叠。

Creating a subplot will delete any pre-existing subplot that overlaps with it beyond sharing a boundary.

import matplotlib.pyplot as plt
# plot a line, implicitly creating a subplot(111)
plt.plot([1,2,3])
# now create a subplot which represents the top plot of a grid with 2 rows and 1 column.
#Since this subplot will overlap the first, the plot (and its axes) previously
created, will be removed
plt.subplot(211)
plt.plot(range(12))
plt.subplot(212, facecolor='y') # creates 2nd subplot with yellow background
plt.plot(range(12))

上述代码行生成以下输出 -

The above line of code generates the following output −

mutliplots

图形类的add_subplot()函数不会覆盖现有绘图:

The add_subplot() function of the figure class will not overwrite the existing plot −

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot([1,2,3])
ax2 = fig.add_subplot(221, facecolor='y')
ax2.plot([1,2,3])

当执行上述代码行时,它生成以下输出:

When the above line of code is executed, it generates the following output −

add subplot function

您可以通过在同一图形画布中添加另一个Axes对象,在同一图形中添加一个插入绘图。

You can add an insert plot in the same figure by adding another axes object in the same figure canvas.

import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig=plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.55, 0.55, 0.3, 0.3]) # inset axes
y = np.sin(x)
axes1.plot(x, y, 'b')
axes2.plot(x,np.cos(x),'r')
axes1.set_title('sine')
axes2.set_title("cosine")
plt.show()

当执行上述代码行时,生成以下输出:

Upon execution of the above line of code, the following output is generated −

insert plot

Matplotlib - Subplots() Function

Matplotlib 的 pyplot API 有一个名为 subplots() 的便捷函数,它充当一个实用程序包装器,并有助于在一个调用中创建子图的常用布局,包括包围图形对象。

Matplotlib’spyplot API has a convenience function called subplots() which acts as a utility wrapper and helps in creating common layouts of subplots, including the enclosing figure object, in a single call.

Plt.subplots(nrows, ncols)

此函数的两个整型参数指定子图网格的行数和列数。该函数返回一个图形对象和一个包含与 nrows*ncols 相等的轴对象元组。每个轴对象都可以通过其索引进行访问。在这里,我们创建了一个 2 行 2 列的子图,并在每个子图中显示 4 个不同的绘图。

The two integer arguments to this function specify the number of rows and columns of the subplot grid. The function returns a figure object and a tuple containing axes objects equal to nrows*ncols. Each axes object is accessible by its index. Here we create a subplot of 2 rows by 2 columns and display 4 different plots in each subplot.

import matplotlib.pyplot as plt
fig,a =  plt.subplots(2,2)
import numpy as np
x = np.arange(1,5)
a[0][0].plot(x,x*x)
a[0][0].set_title('square')
a[0][1].plot(x,np.sqrt(x))
a[0][1].set_title('square root')
a[1][0].plot(x,np.exp(x))
a[1][0].set_title('exp')
a[1][1].plot(x,np.log10(x))
a[1][1].set_title('log')
plt.show()

上述代码行生成以下输出 -

The above line of code generates the following output −

subplots function

Matplotlib - Subplot2grid() Function

此函数在网格的特定位置创建Axes对象时具有更大的灵活性。它还允许Axes对象跨多个行或列。

This function gives more flexibility in creating an axes object at a specific location of the grid. It also allows the axes object to be spanned across multiple rows or columns.

Plt.subplot2grid(shape, location, rowspan, colspan)

在下面的示例中,将一个图对象网格填充到具有不同大小的轴对象,并分布在行和列跨度中,每个都显示不同的绘图。

In the following example, a 3X3 grid of the figure object is filled with axes objects of varying sizes in row and column spans, each showing a different plot.

import matplotlib.pyplot as plt
a1 = plt.subplot2grid((3,3),(0,0),colspan = 2)
a2 = plt.subplot2grid((3,3),(0,2), rowspan = 3)
a3 = plt.subplot2grid((3,3),(1,0),rowspan = 2, colspan = 2)
import numpy as np
x = np.arange(1,10)
a2.plot(x, x*x)
a2.set_title('square')
a1.plot(x, np.exp(x))
a1.set_title('exp')
a3.plot(x, np.log(x))
a3.set_title('log')
plt.tight_layout()
plt.show()

执行以上行代码之后,会生成以下输出 -

Upon execution of the above line code, the following output is generated −

subplots 2 grid function

Matplotlib - Grids

设置轴对象的 grid() 函数打开或关闭图中的网格可见性。您还可以显示网格的主要/次要(或两者)标记。此外,可以在 grid() 函数中设置颜色、线条样式和线条宽度属性。

The grid() function of axes object sets visibility of grid inside the figure to on or off. You can also display major / minor (or both) ticks of the grid. Additionally color, linestyle and linewidth properties can be set in the grid() function.

import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(1,3, figsize = (12,4))
x = np.arange(1,11)
axes[0].plot(x, x**3, 'g',lw=2)
axes[0].grid(True)
axes[0].set_title('default grid')
axes[1].plot(x, np.exp(x), 'r')
axes[1].grid(color='b', ls = '-.', lw = 0.25)
axes[1].set_title('custom grid')
axes[2].plot(x,x)
axes[2].set_title('no grid')
fig.tight_layout()
plt.show()
grids

Matplotlib - Formatting Axes

有时候,一个或几个点会远大于大部分数据。在这种情况下,轴的比例需要设置为对数比例,而不是普通比例。这是对数比例。在 Matplotlib 中,可以通过将轴对象的 xscale 或 vscale 属性设置为“log”来实现。

Sometimes, one or a few points are much larger than the bulk of data. In such a case, the scale of an axis needs to be set as logarithmic rather than the normal scale. This is the Logarithmic scale. In Matplotlib, it is possible by setting xscale or vscale property of axes object to ‘log’.

还需要在轴号和轴标签之间显示一些额外距离。可以将任一轴(x 或 y 或两者)的 labelpad 属性设置为所需值。

It is also required sometimes to show some additional distance between axis numbers and axis label. The labelpad property of either axis (x or y or both) can be set to the desired value.

以上两个特性的演示借助以下示例实现。右侧的子图具有对数比例,而左侧的子图的 x 轴具有距离较大的标签。

Both the above features are demonstrated with the help of the following example. The subplot on the right has a logarithmic scale and one on left has its x axis having label at more distance.

import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(1, 2, figsize=(10,4))
x = np.arange(1,5)
axes[0].plot( x, np.exp(x))
axes[0].plot(x,x**2)
axes[0].set_title("Normal scale")
axes[1].plot (x, np.exp(x))
axes[1].plot(x, x**2)
axes[1].set_yscale("log")
axes[1].set_title("Logarithmic scale (y)")
axes[0].set_xlabel("x axis")
axes[0].set_ylabel("y axis")
axes[0].xaxis.labelpad = 10
axes[1].set_xlabel("x axis")
axes[1].set_ylabel("y axis")
plt.show()
formatting axes

轴脊线是连接轴刻度的分界绘图区域边界的线。轴对象具有位于顶部、底部、左侧和右侧的脊线。

Axis spines are the lines connecting axis tick marks demarcating boundaries of plot area. The axes object has spines located at top, bottom, left and right.

可以通过指定颜色和宽度来绘制每个脊线。如果颜色设置为无,则任何边都不可见。

Each spine can be formatted by specifying color and width. Any edge can be made invisible if its color is set to none.

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.spines['bottom'].set_color('blue')
ax.spines['left'].set_color('red')
ax.spines['left'].set_linewidth(2)
ax.spines['right'].set_color(None)
ax.spines['top'].set_color(None)
ax.plot([1,2,3,4,5])
plt.show()
axis spines

Matplotlib - Setting Limits

Matplotlib 自动到达要沿绘图的 x、y(以及在 3D 绘图的情况下为 z 轴)轴显示的变量的最小值和最大值。然而,可以通过使用 set_xlim()set_ylim() 函数明确设置限制。

Matplotlib automatically arrives at the minimum and maximum values of variables to be displayed along x, y (and z axis in case of 3D plot) axes of a plot. However, it is possible to set the limits explicitly by using set_xlim() and set_ylim() functions.

在以下绘图中,显示了 x 和 y 轴的自动比例限制 -

In the following plot, the autoscaled limits of x and y axes are shown −

import matplotlib.pyplot as plt
fig = plt.figure()
a1 = fig.add_axes([0,0,1,1])
import numpy as np
x = np.arange(1,10)
a1.plot(x, np.exp(x))
a1.set_title('exp')
plt.show()
setting limits

现在我们设置 x 轴上的限制为 (0 到 10) 以及 y 轴上的限制 (0 到 10000) -

Now we format the limits on x axis to (0 to 10) and y axis (0 to 10000) −

import matplotlib.pyplot as plt
fig = plt.figure()
a1 = fig.add_axes([0,0,1,1])
import numpy as np
x = np.arange(1,10)
a1.plot(x, np.exp(x),'r')
a1.set_title('exp')
a1.set_ylim(0,10000)
a1.set_xlim(0,10)
plt.show()
format the limits

Matplotlib - Setting Ticks and Tick Labels

刻度是标记轴上数据点的标记。到目前为止,在所有之前的示例中,Matplotlib 一直自动执行在轴上对点进行间距的任务。Matplotlib 的默认刻度定位器和格式化程序设计为在许多常见情况下通常足够。可以明确提及刻度的位置和标签,以满足特定要求。

Ticks are the markers denoting data points on axes. Matplotlib has so far - in all our previous examples - automatically taken over the task of spacing points on the axis.Matplotlib’s default tick locators and formatters are designed to be generally sufficient in many common situations. Position and labels of ticks can be explicitly mentioned to suit specific requirements.

xticks()yticks() 函数采用列表对象作为参数。列表中的元素表示将显示刻度的相应操作的位置。

The xticks() and yticks() function takes a list object as argument. The elements in the list denote the positions on corresponding action where ticks will be displayed.

ax.set_xticks([2,4,6,8,10])

此方法将用刻度标记给定位置的数据点。

This method will mark the data points at the given positions with ticks.

类似地,可以通过 set_xlabels()set_ylabels() 函数分别设置与刻度标记对应的标签。

Similarly, labels corresponding to tick marks can be set by set_xlabels() and set_ylabels() functions respectively.

ax.set_xlabels([‘two’, ‘four’,’six’, ‘eight’, ‘ten’])

这将在 x 轴上的标记下面显示文本标签。

This will display the text labels below the markers on the x axis.

以下示例演示了刻度和标签的使用。

Following example demonstrates the use of ticks and labels.

import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
y = np.sin(x)
ax.plot(x, y)
ax.set_xlabel(‘angle’)
ax.set_title('sine')
ax.set_xticks([0,2,4,6])
ax.set_xticklabels(['zero','two','four','six'])
ax.set_yticks([-1,0,1])
plt.show()
ticks and labels

Matplotlib - Twin Axes

在图中拥有双 x 或 y 轴被认为是有用的。更重要的是,当一起绘制具有不同单位的曲线时。Matplotlib 使用 twinx 和 twiny 函数支持此功能。

It is considered useful to have dual x or y axes in a figure. Moreso, when plotting curves with different units together. Matplotlib supports this with the twinxand twiny functions.

在以下示例中,绘图具有双 y 轴,一个显示 exp(x),另一个显示 log(x) -

In the following example, the plot has dual y axes, one showing exp(x) and the other showing log(x) −

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
a1 = fig.add_axes([0,0,1,1])
x = np.arange(1,11)
a1.plot(x,np.exp(x))
a1.set_ylabel('exp')
a2 = a1.twinx()
a2.plot(x, np.log(x),'ro-')
a2.set_ylabel('log')
fig.legend(labels = ('exp','log'),loc='upper left')
plt.show()
twin axes

Matplotlib - Bar Plot

条形图或条形图是一种用矩形条形表示分类数据的图表,其高度或长度与它们所代表的值成正比。这些条形可以垂直或水平绘制。

A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally.

条形图显示了离散类别之间的比较。图表的一个轴显示正在比较的特定类别,另一个轴则表示测量值。

A bar graph shows comparisons among discrete categories. One axis of the chart shows the specific categories being compared, and the other axis represents a measured value.

Matplotlib API 提供了 bar() 函数,该函数可以用在 MATLAB 样式中,也可以用在面向对象的 API 中。与轴对象一起使用的 bar() 函数的签名如下 -

Matplotlib API provides the bar() function that can be used in the MATLAB style use as well as object oriented API. The signature of bar() function to be used with axes object is as follows −

ax.bar(x, height, width, bottom, align)

函数创建具有大小为 (x −width = 2; x + width=2; bottom; bottom + height) 的绑定矩形的条形图。

The function makes a bar plot with the bound rectangle of size (x −width = 2; x + width=2; bottom; bottom + height).

传递给该函数的参数为 -

The parameters to the function are −

x

sequence of scalars representing the x coordinates of the bars. align controls if x is the bar center (default) or left edge.

height

scalar or sequence of scalars representing the height(s) of the bars.

width

scalar or array-like, optional. the width(s) of the bars default 0.8

bottom

scalar or array-like, optional. the y coordinate(s) of the bars default None.

align

{‘center’, ‘edge’}, optional, default ‘center’

函数返回一个包含所有条形的 Matplotlib 容器对象。

The function returns a Matplotlib container object with all bars.

以下是 Matplotlib 条形图的一个简单示例。它显示了一所学院提供的各种课程的注册学生数量。

Following is a simple example of the Matplotlib bar plot. It shows the number of students enrolled for various courses offered at an institute.

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.bar(langs,students)
plt.show()
matplotlib bar plot

当比较多个量并且更改一个变量时,我们可能需要一个条形图,其中条形具有一个量值的颜色。

When comparing several quantities and when changing one variable, we might want a bar chart where we have bars of one color for one quantity value.

我们可以通过改变条形的厚度和位置来绘制多个条形图。data 变量包含三个系列,每个系列有四个值。下面的脚本将显示三个由四个条形组成的条形图。条形的厚度为 0.25 个单位。每个条形图将比前一个条形图偏移 0.25 个单位。data 对象是一个多字典,其中包含过去四年里三所工程学院通过的学生人数。

We can plot multiple bar charts by playing with the thickness and the positions of the bars. The data variable contains three series of four values. The following script will show three bar charts of four bars. The bars will have a thickness of 0.25 units. Each bar chart will be shifted 0.25 units from the previous one. The data object is a multidict containing number of students passed in three branches of an engineering college over the last four years.

import numpy as np
import matplotlib.pyplot as plt
data = [[30, 25, 50, 20],
[40, 23, 51, 17],
[35, 22, 45, 19]]
X = np.arange(4)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(X + 0.00, data[0], color = 'b', width = 0.25)
ax.bar(X + 0.25, data[1], color = 'g', width = 0.25)
ax.bar(X + 0.50, data[2], color = 'r', width = 0.25)
multiple bar charts

堆叠式条形图在彼此顶部堆叠了表示不同组的条形。结果条形的高度显示了各组的综合结果。

The stacked bar chart stacks bars that represent different groups on top of each other. The height of the resulting bar shows the combined result of the groups.

pyplot.bar() 的可选底部参数允许你为条形指定一个起始值。它不会从零开始再扩展到某个值,而是从底部扩展到该值。对 pyplot.bar() 的第一次调用绘制蓝色条形。对 pyplot.bar() 的第二次调用绘制红色条形,底部位于蓝色条形的顶部。

The optional bottom parameter of the pyplot.bar() function allows you to specify a starting value for a bar. Instead of running from zero to a value, it will go from the bottom to the value. The first call to pyplot.bar() plots the blue bars. The second call to pyplot.bar() plots the red bars, with the bottom of the blue bars being at the top of the red bars.

import numpy as np
import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
ind = np.arange(N) # the x locations for the groups
width = 0.35
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(ind, menMeans, width, color='r')
ax.bar(ind, womenMeans, width,bottom=menMeans, color='b')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
ax.set_yticks(np.arange(0, 81, 10))
ax.legend(labels=['Men', 'Women'])
plt.show()
scores

Matplotlib - Histogram

直方图是数值数据分布的准确表示。它是连续变量的概率分布的估计。它是一种条形图。

A histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable. It is a kind of bar graph.

要构建直方图,请按照以下步骤操作:

To construct a histogram, follow these steps −

  1. Bin the range of values.

  2. Divide the entire range of values into a series of intervals.

  3. Count how many values fall into each interval.

这些区间通常被指定为变量的连续、非重叠的区间。

The bins are usually specified as consecutive, non-overlapping intervals of a variable.

matplotlib.pyplot.hist() 函数绘制直方图。它计算并绘制 x 的直方图。

The matplotlib.pyplot.hist() function plots a histogram. It computes and draws the histogram of x.

Parameters

下表列出了直方图的参数:

The following table lists down the parameters for a histogram −

x

array or sequence of arrays

bins

integer or sequence or ‘auto’, optional

optional parameters

range

The lower and upper range of the bins.

density

If True, the first element of the return tuple will be the counts normalized to form a probability density

cumulative

If True, then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values.

histtype

以下示例绘制了学生在课堂上获得的成绩直方图。定义了四个箱子,0-25、26-50、51-75 和 76-100。直方图显示了落在这个范围内的学生人数。

Following example plots a histogram of marks obtained by students in a class. Four bins, 0-25, 26-50, 51-75, and 76-100 are defined. The Histogram shows number of students falling in this range.

from matplotlib import pyplot as plt
import numpy as np
fig,ax = plt.subplots(1,1)
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
ax.hist(a, bins = [0,25,50,75,100])
ax.set_title("histogram of result")
ax.set_xticks([0,25,50,75,100])
ax.set_xlabel('marks')
ax.set_ylabel('no. of students')
plt.show()

该图如下所示显示 −

The plot appears as shown below −

histogram

Matplotlib - Pie Chart

饼图只能显示一个数据系列。饼图显示了一个数据系列中各个项目(称为饼片)的大小,与各个项目总数成比例。饼图中的数据点显示为整个饼图中的百分比。

A Pie Chart can only display one series of data. Pie charts show the size of items (called wedge) in one data series, proportional to the sum of the items. The data points in a pie chart are shown as a percentage of the whole pie.

Matplotlib API 有一个 pie() 函数,该函数生成一个饼图,表示数组中的数据。每个饼片的部分面积由 x/sum(x) 给出。如果 sum(x)< 1,那么 x 的值将直接给出部分面积,并且数组不会规范化。生成的饼将包含大小为 1 - sum(x) 的空白饼片。

Matplotlib API has a pie() function that generates a pie diagram representing data in an array. The fractional area of each wedge is given by x/sum(x). If sum(x)< 1, then the values of x give the fractional area directly and the array will not be normalized. Theresulting pie will have an empty wedge of size 1 - sum(x).

如果图形和坐标轴为方形,或者坐标轴的纵横比相等,则饼图看起来效果最佳。

The pie chart looks best if the figure and axes are square, or the Axes aspect is equal.

Parameters

下表列出了饼图的参数 −

Following table lists down the parameters foe a pie chart −

x

array-like. The wedge sizes.

labels

list. A sequence of strings providing the labels for each wedge.

Colors

A sequence of matplotlibcolorargs through which the pie chart will cycle. If None, will use the colors in the currently active cycle.

Autopct

string, used to label the wedges with their numeric value. The label will be placed inside the wedge. The format string will be fmt%pct.

以下代码使用 pie() 函数来显示注册各种计算机语言课程的学生列表的饼图。比例百分比显示在相应饼片内,这借助于 autopct 参数实现,该参数设置为 %1.2f%。

Following code uses the pie() function to display the pie chart of the list of students enrolled for various computer language courses. The proportionate percentage is displayed inside the respective wedge with the help of autopct parameter which is set to %1.2f%.

from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.pie(students, labels = langs,autopct='%1.2f%%')
plt.show()
pie chart

Matplotlib - Scatter Plot

散点图用于在水平轴和垂直轴上绘图数据点,以试图显示一个变量在一个多么大的程度上受到另一个变量的影响。数据表中的每一行均由标记器表示,其位置取决于它在 X 轴和 Y 轴上设置的列中的值。可以设置第三个变量以对应于标记器的颜色或大小,从而为绘图添加另一个维度。

Scatter plots are used to plot data points on horizontal and vertical axis in the attempt to show how much one variable is affected by another. Each row in the data table is represented by a marker the position depends on its values in the columns set on the X and Y axes. A third variable can be set to correspond to the color or size of the markers, thus adding yet another dimension to the plot.

下面的脚本绘制了两个不同颜色中男孩和女孩的成绩范围与成绩的散点图。

The script below plots a scatter diagram of grades range vs grades of boys and girls in two different colors.

import matplotlib.pyplot as plt
girls_grades = [89, 90, 70, 89, 100, 80, 90, 100, 80, 34]
boys_grades = [30, 29, 49, 48, 100, 48, 38, 45, 20, 30]
grades_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.scatter(grades_range, girls_grades, color='r')
ax.scatter(grades_range, boys_grades, color='b')
ax.set_xlabel('Grades Range')
ax.set_ylabel('Grades Scored')
ax.set_title('scatter plot')
plt.show()
graded scored

Matplotlib - Contour Plot

等高线图(有时称为水平图)是一种在二维平面上显示三维曲面的方法。它在 y 轴上绘制两个预测变量 X Y 和一个响应变量 Z 作为等高线。这些等高线有时称为 z 切片或等响应值。

Contour plots (sometimes called Level Plots) are a way to show a three-dimensional surface on a two-dimensional plane. It graphs two predictor variables X Y on the y-axis and a response variable Z as contours. These contours are sometimes called the z-slices or the iso-response values.

如果您想了解值 Z 如何随两个输入 X 和 Y 的函数而变化,并且 Z = f(X,Y),则等高线图就是合适的。双变量函数的一个等高线或等值线是一条曲线,沿该曲线该函数具有一个常数值。

A contour plot is appropriate if you want to see how alue Z changes as a function of two inputs X and Y, such that Z = f(X,Y). A contour line or isoline of a function of two variables is a curve along which the function has a constant value.

自变量 x 和 y 通常限制在一个称为网格的规则网格中。numpy.meshgrid 由一个 x 值数组和一个 y 值数组创建一个矩形网格。

The independent variables x and y are usually restricted to a regular grid called meshgrid. The numpy.meshgrid creates a rectangular grid out of an array of x values and an array of y values.

Matplotlib API 包含 contour() 和 contourf() 函数,它们分别绘制等高线和填充等高线。这两个函数都需要三个参数 x、y 和 z。

Matplotlib API contains contour() and contourf() functions that draw contour lines and filled contours, respectively. Both functions need three parameters x,y and z.

import numpy as np
import matplotlib.pyplot as plt
xlist = np.linspace(-3.0, 3.0, 100)
ylist = np.linspace(-3.0, 3.0, 100)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X**2 + Y**2)
fig,ax=plt.subplots(1,1)
cp = ax.contourf(X, Y, Z)
fig.colorbar(cp) # Add a colorbar to a plot
ax.set_title('Filled Contours Plot')
#ax.set_xlabel('x (cm)')
ax.set_ylabel('y (cm)')
plt.show()
filled colours plot

Matplotlib - Quiver Plot

颤动图显示了速度矢量,即在点 (x,y) 具有分量 (u,v) 的箭头。

A quiver plot displays the velocity vectors as arrows with components (u,v) at the points (x,y).

quiver(x,y,u,v)

以上命令将矢量绘制成箭头,箭头位于 x 和 y 中每个相应元素对指定坐标处。

The above command plots vectors as arrows at the coordinates specified in each corresponding pair of elements in x and y.

Parameters

下表列出了颤动图的不同参数 −

The following table lists down the different parameters for the Quiver plot −

x

1D or 2D array, sequence. The x coordinates of the arrow locations

y

1D or 2D array, sequence. The y coordinates of the arrow locations

u

1D or 2D array, sequence. The x components of the arrow vectors

v

1D or 2D array, sequence. The y components of the arrow vectors

c

1D or 2D array, sequence. The arrow colors

以下代码绘制了一个简单的羽化图 −

The following code draws a simple quiver plot −

import matplotlib.pyplot as plt
import numpy as np
x,y = np.meshgrid(np.arange(-2, 2, .2), np.arange(-2, 2, .25))
z = x*np.exp(-x**2 - y**2)
v, u = np.gradient(z, .2, .2)
fig, ax = plt.subplots()
q = ax.quiver(x,y,u,v)
plt.show()
quiver plot

Matplotlib - Box Plot

箱形图也称为须图,它显示了一组包含最小值、第一四分位数、中位数、第三四分位数和最大值的数据的摘要。在一个箱形图中,我们绘制从第一四分位数到第三四分位数的箱子。一条垂直线穿过中位数处的箱子。垂直线从每个四分位数延伸到最小值或最大值。

A box plot which is also known as a whisker plot displays a summary of a set of data containing the minimum, first quartile, median, third quartile, and maximum. In a box plot, we draw a box from the first quartile to the third quartile. A vertical line goes through the box at the median. The whiskers go from each quartile to the minimum or maximum.

box plot

让我们创建箱线图的数据。我们使用 numpy.random.normal() 函数创建虚假数据。它接收三个参数,即正态分布的均值和标准差,以及所需值的数量。

Let us create the data for the boxplots. We use the numpy.random.normal() function to create the fake data. It takes three arguments, mean and standard deviation of the normal distribution, and the number of values desired.

np.random.seed(10)
collectn_1 = np.random.normal(100, 10, 200)
collectn_2 = np.random.normal(80, 30, 200)
collectn_3 = np.random.normal(90, 20, 200)
collectn_4 = np.random.normal(70, 25, 200)

我们在上面创建的数组列表是创建箱线图的唯一所需输入。使用 data_to_plot 代码行,我们可以使用以下代码创建箱线图 −

The list of arrays that we created above is the only required input for creating the boxplot. Using the data_to_plot line of code, we can create the boxplot with the following code −

fig = plt.figure()
# Create an axes instance
ax = fig.add_axes([0,0,1,1])
# Create the boxplot
bp = ax.boxplot(data_to_plot)
plt.show()

上述代码行将生成以下输出 −

The above line of code will generate the following output −

line of code

Matplotlib - Violin Plot

小提琴图类似于箱线图,但它们还会显示不同值处的数据概率密度。这些图中包含数据的中间值标记和表示四分位数范围的方框,如标准箱线图中的那样。在此箱线图上叠加核密度估计。与箱线图一样,小提琴图用于表示不同“类别”中的变量分布(或样本分布)的比较。

Violin plots are similar to box plots, except that they also show the probability density of the data at different values. These plots include a marker for the median of the data and a box indicating the interquartile range, as in the standard box plots. Overlaid on this box plot is a kernel density estimation. Like box plots, violin plots are used to represent comparison of a variable distribution (or sample distribution) across different "categories".

小提琴图比普通箱线图信息更多。事实上,虽然箱线图仅显示均值/中位数和四分位数范围等汇总统计信息,但小提琴图显示数据的完整分布。

A violin plot is more informative than a plain box plot. In fact while a box plot only shows summary statistics such as mean/median and interquartile ranges, the violin plot shows the full distribution of the data.

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(10)
collectn_1 = np.random.normal(100, 10, 200)
collectn_2 = np.random.normal(80, 30, 200)
collectn_3 = np.random.normal(90, 20, 200)
collectn_4 = np.random.normal(70, 25, 200)

## combine these different collections into a list
data_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4]

# Create a figure instance
fig = plt.figure()

# Create an axes instance
ax = fig.add_axes([0,0,1,1])

# Create the boxplot
bp = ax.violinplot(data_to_plot)
plt.show()
violin plot

Matplotlib - Three-dimensional Plotting

尽管 Matplotlib 最初仅设计为二维绘图,但在后续版本中,一些三维绘图实用工具已构建在 Matplotlib 的二维显示之上,以提供一些用于三维数据可视化的工具。通过导入 mplot3d toolkit (包含在 Matplotlib 包中)来启用三维绘图。

Even though Matplotlib was initially designed with only two-dimensional plotting in mind, some three-dimensional plotting utilities were built on top of Matplotlib’s two-dimensional display in later versions, to provide a set of tools for three-dimensional data visualization. Three-dimensional plots are enabled by importing the mplot3d toolkit, included with the Matplotlib package.

可以通过将关键字 projection='3d' 传递给任何常规轴创建例程来创建三维轴。

A three-dimensional axes can be created by passing the keyword projection='3d' to any of the normal axes creation routines.

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
z = np.linspace(0, 1, 100)
x = z * np.sin(20 * z)
y = z * np.cos(20 * z)
ax.plot3D(x, y, z, 'gray')
ax.set_title('3D line plot')
plt.show()

我们现在可以绘制各种三维绘图类型。最基本的三维绘图是 3D line plot ,它由 (x, y, z) 三元组集创建。这可以使用 ax.plot3D 函数创建。

We can now plot a variety of three-dimensional plot types. The most basic three-dimensional plot is a 3D line plot created from sets of (x, y, z) triples. This can be created using the ax.plot3D function.

three dimensional plotting

3D scatter plot 是使用 ax.scatter3D 函数生成的。

3D scatter plot is generated by using the ax.scatter3D function.

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
z = np.linspace(0, 1, 100)
x = z * np.sin(20 * z)
y = z * np.cos(20 * z)
c = x + y
ax.scatter(x, y, z, c=c)
ax.set_title('3d Scatter plot')
plt.show()
3d scatter plot

Matplotlib - 3D Contour Plot

ax.contour3D() 函数创建三维等值线图。它要求所有输入数据都采用二维规则网格的形式,并在每个点计算 Z 数据。这里,我们将显示三维正弦函数的三维等值线图。

The ax.contour3D() function creates three-dimensional contour plot. It requires all the input data to be in the form of two-dimensional regular grids, with the Z-data evaluated at each point. Here, we will show a three-dimensional contour diagram of a three-dimensional sinusoidal function.

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
def f(x, y):
   return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='binary')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title('3D contour')
plt.show()
3d contour

Matplotlib - 3D Wireframe plot

线框图使用一组值并将其投影到指定的三维曲面上,并且可以使生成的三维形式非常易于可视化。 plot_wireframe() 函数用于此目的 −

Wireframe plot takes a grid of values and projects it onto the specified three-dimensional surface, and can make the resulting three-dimensional forms quite easy to visualize. The plot_wireframe() function is used for the purpose −

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
def f(x, y):
   return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_wireframe(X, Y, Z, color='black')
ax.set_title('wireframe')
plt.show()

上述代码行将生成以下输出 −

The above line of code will generate the following output −

wireframe

Matplotlib - 3D Surface plot

曲面图显示指定因变量 (Y) 和两个自变量 (X 和 Z) 之间的功能关系。该图是等值线图的伴图。曲面图类似于线框图,但线框的每个面都是填充的多边形。这有助于感知正在可视化的曲面的拓扑。 plot_surface() 函数以 x、y 和 z 为参数。

Surface plot shows a functional relationship between a designated dependent variable (Y), and two independent variables (X and Z). The plot is a companion plot to the contour plot. A surface plot is like a wireframe plot, but each face of the wireframe is a filled polygon. This can aid perception of the topology of the surface being visualized. The plot_surface() function x,y and z as arguments.

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
x = np.outer(np.linspace(-2, 2, 30), np.ones(30))
y = x.copy().T # transpose
z = np.cos(x ** 2 + y ** 2)

fig = plt.figure()
ax = plt.axes(projection='3d')

ax.plot_surface(x, y, z,cmap='viridis', edgecolor='none')
ax.set_title('Surface plot')
plt.show()

上述代码行将生成以下输出 −

The above line of code will generate the following output −

surface plot

Matplotlib - Working With Text

Matplotlib 具有广泛的文本支持,包括:数学表达式的支持、对栅格和矢量输出的支持、任意旋转的新行分隔文本以及 Unicode 支持。Matplotlib 包含其自己的 matplotlib.font_manager,它实现了一个跨平台、符合 W3C 的字体查找算法。

Matplotlib has extensive text support, including support for mathematical expressions, TrueType support for raster and vector outputs, newline separated text with arbitrary rotations, and unicode support. Matplotlib includes its own matplotlib.font_manager which implements a cross platform, W3C compliant font finding algorithm.

用户可以很好地控制文本属性(字体大小、字体粗细、文本位置和颜色等)。Matplotlib 实现了大量的 TeX 数学符号和命令。

The user has a great deal of control over text properties (font size, font weight, text location and color, etc.). Matplotlib implements a large number of TeX math symbols and commands.

以下命令列表用于在 Pyplot 界面中创建文本 -

The following list of commands are used to create text in the Pyplot interface −

text

Add text at an arbitrary location of the Axes.

annotate

Add an annotation, with an optional arrow, at an arbitrary location of theAxes.

xlabel

Add a label to the Axes’s x-axis.

ylabel

Add a label to the Axes’s y-axis.

title

Add a title to the Axes.

figtext

Add text at an arbitrary location of the Figure.

suptitle

Add a title to the Figure.

所有这些函数都创建并返回一个 matplotlib.text.Text() 实例。

All of these functions create and return a matplotlib.text.Text() instance.

以下脚本演示了上述一些函数的使用情况:

Following scripts demonstrate the use of some of the above functions −

import matplotlib.pyplot as plt
fig = plt.figure()

ax = fig.add_axes([0,0,1,1])

ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
ax.text(3, 8, 'boxed italics text in data coords', style='italic',
bbox = {'facecolor': 'red'})
ax.text(2, 6, r'an equation: $E = mc^2$', fontsize = 15)
ax.text(4, 0.05, 'colored text in axes coords',
verticalalignment = 'bottom', color = 'green', fontsize = 15)
ax.plot([2], [1], 'o')
ax.annotate('annotate', xy = (2, 1), xytext = (3, 4),
arrowprops = dict(facecolor = 'black', shrink = 0.05))
ax.axis([0, 10, 0, 10])
plt.show()

上述代码行将生成以下输出 −

The above line of code will generate the following output −

working with text

Matplotlib - Mathematical Expressions

您可以在任何 Matplotlib 文本字符串中使用子集 TeX 标记,方法是将其放在一对美元符号 ($) 内。

You can use a subset TeXmarkup in any Matplotlib text string by placing it inside a pair of dollar signs ($).

# math text
plt.title(r'$\alpha > \beta$')

要制作下标和上标,请使用 '_' 和 '^' 符号 −

To make subscripts and superscripts, use the '_' and '^' symbols −

r'$\alpha_i> \beta_i$'

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

plt.plot(t,s)
plt.title(r'$\alpha_i> \beta_i$', fontsize=20)

plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$', fontsize = 20)
plt.text(0.1, -0.5, r'$\sqrt{2}$', fontsize=10)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()

上述代码行将生成以下输出 −

The above line of code will generate the following output −

mathematical expressions

Matplotlib - Working with Images

Matplotlib 包中的图像模块提供了加载、重新调整大小和显示图像所需的功能。

The image module in Matplotlib package provides functionalities required for loading, rescaling and displaying image.

Pillow 库支持加载图像数据。默认情况下,Matplotlib 只支持 PNG 图像。如果本机读取失败,下方所示命令将回退到 Pillow。

Loading image data is supported by the Pillow library. Natively, Matplotlib only supports PNG images. The commands shown below fall back on Pillow if the native read fails.

此示例中使用的图像是一个 PNG 文件,但您的数据要记住 Pillow 要求。 imread() 函数用于以 float32 dtype 的 ndarray 对象形式读取图像数据。

The image used in this example is a PNG file, but keep that Pillow requirement in mind for your own data. The imread() function is used to read image data in an ndarray object of float32 dtype.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = mpimg.imread('mtplogo.png')

假设当前工作目录中存在名为 mtplogo.png 的图像。

Assuming that following image named as mtplogo.png is present in the current working directory.

matplotlib image

可以执行 imsave() 函数,将包含图像数据的任何数组保存到磁盘文件中。此处,通过给出 origin 参数作为较低值保存 PNG 原图的垂直翻转版本。

Any array containing image data can be saved to a disk file by executing the imsave() function. Here a vertically flipped version of the original png file is saved by giving origin parameter as lower.

plt.imsave("logo.png", img, cmap = 'gray', origin = 'lower')

如果在新图像查看器中打开,新图像将如下所示。

The new image appears as below if opened in any image viewer.

image viewer

若要在 Matplotlib 查看器上绘制图像,请执行 imshow() 函数。

To draw the image on Matplotlib viewer, execute the imshow() function.

imgplot = plt.imshow(img)

Matplotlib - Transforms

matplotlib 包建立在变换框架之上,可在坐标系统之间轻松移动。可以使用四个坐标系。表中简要介绍了这些系统 −

The matplotlib package is built on top of a transformation framework to easily move between coordinate systems. Four coordinate systems can be used. The systems are described in brief in the table given below −

Coordinate

Transformation Object

Description

Data

ax.transData

The user land data coordinate system. controlled by the xlim and ylim

Axes

ax.transAxes

The coordinate system of the Axes. (0,0) is bottom left and (1,1) is top right of the axes.

Figure

fig.transFigure

The coordinate system of the Figure. (0,0) is bottom left and (1,1) is top right of the figure

display

None

This is the pixel coordinate system of the display. (0,0) is the bottom left and (width, height) is the top right of display in pixels. Alternatively, the(matplotlib.transforms.IdentityTransform()) may be used instead of None.

考虑以下示例 −

Consider the following example −

axes.text(x,y,"my label")

文字放在数据点 (x,y) 的理论位置。因此,我们将谈论“数据坐标”。

The text is placed at the theoretical position of a data point (x,y). Thus we would speak of "data coords".

使用其他变换对象,可以控制位置放置。例如,如果要将上述测试放在轴坐标系的中心,请执行以下代码行:

Using other transformation objects, placement can be controlled. For example, if the above test is to be placed in the centre of axes coordinate system, execute the following line of code −

axes.text(0.5, 0.5, "middle of graph", transform=axes.transAxes)

这些变换可用于任何种类的 Matplotlib 对象。 ax.text 的默认变换为 ax.transDatafig.text 的默认变换为 fig.transFigure.

These transformations can be used for any kind of Matplotlib objects. The default transformation for ax.text is ax.transData and the default transformation for fig.text is fig.transFigure.

轴坐标系在轴中放置文字时非常有用。您可能经常希望在固定位置放置文本气泡;例如,在轴窗格的左上角,并且在您平移或缩放时保持该位置固定。

The axes coordinate system is extremely useful when placing text in your axes. You might often want a text bubble in a fixed location; for example, on the upper left of the axes pane and have that location remain fixed when you pan or zoom.