Matplotlib 简明教程
Matplotlib - Introduction
Matplotlib 是一个功能强大且广泛使用的 Python 绘图库,使我们能够创建各种静态、互动和出版质量的绘图和可视化。它广泛用于数据可视化任务,提供各种功能来创建绘图,如折线图、散点图、条形图、直方图、3D 绘图等等。Matplotlib 库提供灵活性和自定义选项来根据特定需求定制我们的绘图。
Matplotlib is a powerful and widely-used plotting library in Python which enables us to create a variety of static, interactive and publication-quality plots and visualizations. It’s extensively used for data visualization tasks and offers a wide range of functionalities to create plots like line plots, scatter plots, bar charts, histograms, 3D plots and much more. Matplotlib library provides flexibility and customization options to tailor our plots according to specific needs.
它是一个跨平台库,用于从数组中的数据创建 2D 绘图。Matplotlib 用 Python 编写,并使用 NumPy,这是 Python 的数值数学扩展。它提供了一个面向对象 API,该 API 有助于使用 Python GUI 工具包(如 PyQt、WxPythonotTkinter)将绘图嵌入到应用程序中。它可以在 Python 和 IPython Shell 中使用。Jupyter 笔记本和 Web 应用程序服务器也是如此。
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 的过程化界面,该界面旨在类似于由 MathWorks 开发的专有编程语言 MATLAB。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 最常见的途径是通过其 pyplot 模块。
The most common way to use Matplotlib is through its pyplot module.
以下是 Matplotlib 的关键组件和功能的深入概述 −
The following are the in-depth overview of Matplotlib’s key components and functionalities −
Components of Matplotlib
Figure
一个图形是显示我们的绘图或绘图集合的整个窗口或页面。它充当一个容器,包含图形表示的所有元素,包括轴、标签、图例和其他组件。
A figure is the entire window or page that displays our plot or collection of plots. It acts as a container that holds all elements of a graphical representation which includes axes, labels, legends and other components.
这是表示图形的基本绘图。
This is the basic plot which represents the figure.
import matplotlib.pyplot as plt
# Create a new figure
fig = plt.figure()
# Add a plot or subplot to the figure
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
Axes/Subplot
图形中绘制数据的特定区域。图形可以包含多个轴或子绘图。以下是轴/子绘图的示例。
A specific region of the figure in which the data is plotted. Figures can contain multiple axes or subplots. The following is the example of the axes/subplot.
Example
import matplotlib.pyplot as plt
# Creating a 2x2 grid of subplots
fig, axes = plt.subplots(nrows=2, ncols=2)
# Accessing individual axes (subplots)
axes[0, 0].plot([1, 2, 3], [4, 5, 6]) # Plot in the first subplot (top-left)
axes[0, 1].scatter([1, 2, 3], [4, 5, 6]) # Second subplot (top-right)
axes[1, 0].bar([1, 2, 3], [4, 5, 6]) # Third subplot (bottom-left)
axes[1, 1].hist([1, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5]) # Fourth subplot (bottom-right)
plt.show()
Axis
轴是指绘图中的 X 轴或 Y 轴,或者它也可以表示一组子绘图中的单个轴。了解轴对于控制和自定义 Matplotlib 中绘图的外观和行为至关重要。以下是包含轴的绘图。
An axis refers to the X-axis or Y-axis in a plot or it can also denote an individual axis within a set of subplots. Understanding axes is essential for controlling and customizing the appearance and behavior of plots in Matplotlib. The following is the plot which contains the axis.
Artist
艺术家是指构成绘图的各个组件或实体,如图形、轴、线、文本、块、形状(矩形或圆形)等。它们是用于创建可视化的构建模块,并按层次组织。
Artists refer to the various components or entities that make up a plot such as figures, axes, lines, text, patches, shapes (rectangles or circles) and more. They are the building blocks used to create visualizations and are organized in a hierarchy.
以下是类似于艺术家所有组件的绘图。
The below is the plot which resembles all the components of an artist.
Example
import matplotlib.pyplot as plt
# Create a figure and an axis (subplot)
fig, ax = plt.subplots()
# Plot a line (artist)
line = ax.plot([1, 2, 3], [4, 5, 6], label='Line')[0]
# Modify line properties
line.set_color('red')
line.set_linewidth(2.5)
# Add labels and title (text artists)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_title('Artist Plot')
plt.legend()
plt.show()
Key Features
-
Simple Plotting − Matplotlib allows us to create basic plots easily with just a few lines of code.
-
Customization − We can extensively customize plots by adjusting colors, line styles, markers, labels, titles and more.
-
Multiple Plot Types − It supports a wide variety of plot types such as line plots, scatter plots, bar charts, histograms, pie charts, 3D plots, etc.
-
Publication Quality − Matplotlib produces high-quality plots suitable for publications and presentations with customizable DPI settings.
-
Support for LaTeX Typesetting − We can use LaTeX for formatting text and mathematical expressions in plots.
Types of Plots
Matplotlib 支持以下提到的各种类型的绘图。每个绘图类型在库中都有自己独特的函数。
Matplotlib supports various types of plots which are as mentioned below. Each plot type has its own function in the library.
Name of the plot |
Definition |
Image |
Line plot |
A line plot is a type of graph that displays data points connected by straight line segments. The plt.plot() function of the matplotlib library is used to create the line plot. |
|
Scatter plot |
A scatter plot is a type of graph that represents individual data points by displaying them as markers on a two-dimensional plane. The plt.scatter() function is used to plot the scatter plot. |
|
Line plot |
A line plot is a type of graph that displays data points connected by straight line segments. The plt.plot() function of the matplotlib library is used to create the line plot. |
|
Bar plot |
A bar plot or bar chart is a visual representation of categorical data using rectangular bars. The plt.bar() function is used to plot the bar plot. |
|
Pie plot |
A pie plot is also known as a pie chart. It is a circular statistical graphic used to illustrate numerical proportions. It divides a circle into sectors or slices to represent the relative sizes or percentages of categories within a dataset. The plt.pie() function is used to plot the pie chart. |
上面提到的内容是 Matplotlib 库的基本图表。我们还可以借助 Matplotlib 对三维图表进行可视化。
The above mentioned are the basic plots of the matplotlib library. We can also visualize the 3-d plots with the help of Matplotlib.