Matplotlib中的“ plt”和“ ax”到底是什么?

Indeed, as the most popular and fundamental data visualisation library, Matplotlib is kind of confusing in some perspectives. It is usually to see that someone asking about

的确,作为最受欢迎的基础数据可视化库,Matplotlib在某些方面令人困惑。 通常是看到有人问

  • When should I use “axes”?

    我什么时候应该使用“轴”?
  • Why some examples using “plt” while someone else using “ax”?

    为什么有些示例使用“ plt”,而其他示例使用“ ax”?
  • What’s the difference between them?

    它们之间有什么区别?

It is good that there are so many examples online to show people how to use Matplotlib to draw this kind of chart or that kind of chart, but I rarely see any tutorials mentioning “why”. This may cause people who have less programming experience or switching from other languages like R becomes very confusing.

网上有这么多示例向人们展示了如何使用Matplotlib绘制这种图表或那种图表是很好的,但是我很少看到任何提及“为什么”的教程。 这可能会导致缺乏编程经验或从其他语言(如R)切换的人变得非常混乱。

In this article, I won’t teach you to draw any specific charts using Matplotlib but will try to explain the basic but important regarding Matplotlib — what are the “plt” and “ax” people usually use.

在本文中,我不会教您使用Matplotlib绘制任何特定的图表,而是将尝试解释有关Matplotlib的基本但重要的内容-人们通常使用的“ plt”和“ ax”是什么。

概念 (Concepts)

Image for post
Photo by AbsolutVision on Pixabay
照片由 AbsolutVisionPixabay发布

To clarify, when I say “plt”, it doesn’t exist in the Matplotlib library. It is called “plt” because most of Python programmers like to import Matplotlib and make an alias called “plt”, which I believe you should know, but just in case.

为了澄清,当我说“ plt”时,它在Matplotlib库中不存在。 之所以称为“ plt”,是因为大多数Python程序员喜欢导入Matplotlib并创建一个名为“ plt”的别名,我相信您应该知道,但以防万一。

import matplotlib.pyplot as plt

Then, come back to our main topic. Let’s draw a simple chart for demonstration purposes.

然后,回到我们的主要主题。 让我们为演示目的绘制一个简单的图表。

import numpy as npplt.plot(np.random.rand(20))
plt.title('test title')
plt.show()
Image for post

As shown in the above-annotated screenshot, when we draw a graph using plt:

如上述屏幕截图所示,当我们使用plt绘制图形时:

  1. A Figure object is generated (shown in green)

    生成了Figure对象(以绿色显示)

  2. An Axes object is generated implicitly with the plotted line chart (shown in red)

    使用绘制的折线图隐式生成Axes对象(以红色显示)

  3. All the elements of the plot such as x and y-axis are rendered inside the Axes object (shown in blue)

    绘图的所有元素(例如x和y轴)都呈现在Axes对象内(以蓝色显示)

Well, if we use some kind of metaphor here:

好吧,如果我们在这里使用某种隐喻:

  • Figure is like a paper that you can draw anything you want

    Figure就像一张纸,您可以画任何想要的东西

  • We have to draw a chart in a “cell”, which is Axes in this context

    我们必须在“单元格”中绘制一个图表,在这种情况下为“ Axes

  • If we’re drawing only one graph, we don’t have to draw a “cell” first, just simply draw on the paper anyway. So, we can use plt.plot(...).

    如果仅绘制一个图形,则不必先绘制“单元格”,无论如何只需在纸上绘制即可。 因此,我们可以使用plt.plot(...)

明确画出“单元格” (Explicitly Draw the “Cell”)

Image for post
Photo by LUM3N on Pixabay
照片由 LUM3NPixabay发布

Of course, we can explicitly draw a “cell” on the “paper”, to tell Matplotlib that we’re gonna draw a chart inside this cell. Then, we have the following code.

当然,我们可以在“纸上”显式地绘制一个“单元格”,以告诉Matplotlib我们将在该单元格内绘制一个图表。 然后,我们有以下代码。

fig, ax = plt.subplots()
ax.plot(np.random.rand(20))
ax.set_title('test title')
plt.show()
Image for post

Exactly the same results. The only difference is that we explicitly draw the “cell” so that we are able to get the Figure and Axes object.

完全一样的结果。 唯一的区别是,我们显式绘制了“单元格”,以便能够获得Figure and Axes对象。

Image for post

Indeed, when we just want to plot one graph, it is not necessary to “draw” this cell. However, you must be noticed that we have to do this when we want to draw multiple graphs in one plot. In other words, the subplots.

确实,当我们只想绘制一个图形时,不必“绘制”该单元格。 但是,必须注意,当我们要在一个图中绘制多个图形时,必须这样做。 换句话说,子图。

n_rows = 2
n_cols = 2fig, axes = plt.subplots(n_rows, n_cols)
for row_num in range(n_rows):
for col_num in range(n_cols):
ax = axes[row_num][col_num]
ax.plot(np.random.rand(20))
ax.set_title(f'Plot ({row_num+1}, {col_num+1})')fig.suptitle('Main title')
fig.tight_layout()
plt.show()
Image for post

In this code snippet, we firstly declared how many rows and columns we want to “draw”. 2 by 2 means that we want to draw 4 “cells”.

在此代码段中,我们首先声明了要“绘制”多少行和多少列。 2 by 2表示我们要绘制4个“像元”。

Image for post

Then, in each cell, we plot a random line chart and assign a title based on its row number and column number. Please note that we’re using Axes instances.

然后,在每个单元格中,绘制一个随机折线图,并根据其行号和列号分配标题。 请注意,我们正在使用Axes实例。

After that, we define a “Main title” on the “paper”, which is the Figure instance. So, we have this supertitle that does not belong to any “cell”, but on the paper.

之后,我们在“纸”上定义一个“主要标题”,即Figure实例。 因此,我们拥有这个不属于任何“单元”的标题,而是在纸上。

Finally, before calling the show() method, we need to ask the “paper” — Figure instance — to automatically give enough padding between the cells by calling its tight_layout() method. Otherwise,

最后,在调用show()方法之前,我们需要让“纸张”( Figure实例tight_layout()通过调用其tight_layout()方法自动在单元格之间提供足够的填充。 除此以外,

摘要 (Summary)

Image for post
Photo by bodobe on Pixabay
照片由 bodobePixabay发布

Hopefully, now you understand better what are plt and ax people are using exactly.

我们希望,现在你更好地了解什么是pltax的人都使用完全相同。

Basically, the plt is a common alias of matplotlib.pyplot used by most people. When we plot something using plt such as plt.line(...), we implicitly created a Figure instance and an Axes inside the Figure object. This is totally fine and very convenient when we just want to draw a single graph.

基本上, plt是大多数人使用的matplotlib.pyplot的通用别名。 当我们使用诸如plt.line(...) plt绘制东西时,我们在Figure对象内隐式创建了Figure实例和Axes 。 当我们只想绘制一个图形时,这是非常好的,非常方便。

However, we can explicitly call plt.subplots() to get the Figure object and Axes object, in order to do more things on them. When we want to draw multiple subplots on a Figure, it is usually required to use this approach.

但是,我们可以显式调用plt.subplots()来获取Figure对象和Axes对象,以便对它们执行更多操作。 当我们想在一个Figure上绘制多个子Figure ,通常需要使用此方法。

Also, here are the Matplotlib official API reference for the Figure and Axes classes. It is highly recommended to check them out and try some methods yourselves to make sure you understand even deeper.

另外,这里是FigureAxes类的Matplotlib官方API参考。 强烈建议您检查一下并尝试一些方法,以确保您了解得更深入。

翻译自: https://towardsdatascience.com/what-are-the-plt-and-ax-in-matplotlib-exactly-d2cf4bf164a9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值