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
照片由AbsolutVision在Pixabay上发布

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
照片由LUM3N在Pixabay上发布

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
照片由bodobe在Pixabay上发布

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/388778.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2018年阿里云NoSQL数据库大事盘点

2019独角兽企业重金招聘Python工程师标准>>> NoSQL一词最早出现在1998年。2009年Last.fm的Johan Oskarsson发起了一次关于分布式开源数据库的讨论,来自Rackspace的Eric Evans再次提出了NoSQL概念,这时的NoSQL主要是指非关系型、分布式、不提供…

cayenne:用于随机模拟的Python包

TL;DR; We just released v1.0 of cayenne, our Python package for stochastic simulations! Read on to find out if you should model your system as a stochastic process, and why you should try out cayenne.TL; DR; 我们刚刚发布了 cayenne v1.0 ,这是我们…

java 如何将word 转换为ftl_使用 freemarker导出word文档

近日需要将人员的基本信息导出,存储为word文档,查阅了很多资料,最后选择了使用freemarker,网上一共有四种方式,效果都一样,选择它呢是因为使用简单,再次记录一下,一个简单的demo,仅供…

DotNetBar office2007效果

1.DataGridView 格式化显示cell里的数据日期等。 进入编辑列,选择要设置的列,DefaultCellStyle里->行为->formart设置 2.tabstrip和mdi窗口的结合使用给MDI窗口加上TabPage。拖动个tabstrip到MDI窗口上tabstrip里选择到主窗口名就加上TABPAGE了。d…

spotify 数据分析_没有数据? 没问题! 如何从Wikipedia和Spotify收集重金属数据

spotify 数据分析For many data science students, collecting data is seen as a solved problem. It’s just there in Kaggle or UCI. However, that’s not how data is available daily for working Data Scientists. Also, many of the datasets used for learning have …

IS环境下配置PHP5+MySql+PHPMyAdmin

IIS环境下配置PHP5MySqlPHPMyAdmin Posted on 2009-08-07 15:18 谢启祥 阅读(1385)评论(18) 编辑 收藏 虽然主要是做.net开发的,但是,时不时的还要搞一下php,但是,php在windows下的配置,总是走很多弯路,正好…

kaggle数据集_Kaggle上有170万份ArXiv文章的数据集

kaggle数据集“arXiv is a free distribution service and an open-access archive for 1.7 million scholarly articles in the fields of physics, mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering and sys…

深度学习数据集中数据差异大_使用差异隐私来利用大数据并保留隐私

深度学习数据集中数据差异大The modern world runs on “big data,” the massive data sets used by governments, firms, and academic researchers to conduct analyses, unearth patterns, and drive decision-making. When it comes to data analysis, bigger can be bett…

C#图片处理基本应用(裁剪,缩放,清晰度,水印)

前言 需求源自项目中的一些应用,比如相册功能,通常用户上传相片后我们都会针对该相片再生成一张缩略图,用于其它页面上的列表显示。随便看一下,大部分网站基本都是将原图等比缩放来生成缩略图。但完美主义者会发现一些问题&#…

Java客户端访问HBase集群解决方案(优化)

测试环境&#xff1a;IdeaWindows10 准备工作&#xff1a; <1>、打开本地 C:\Windows\System32\drivers\etc&#xff08;系统默认&#xff09;下名为hosts的系统文件&#xff0c;如果提示当前用户没有权限打开文件&#xff1b;第一种方法是将hosts文件拖到桌面进行配置后…

WPF布局系统

WPF之路——WPF布局系统 前言 前段时间忙了一阵子Google Earth&#xff0c;这周又忙了一阵子架构师论文开题报告&#xff0c;现在终于有时间继续<WPF之路>了。先回忆一下上篇的内容&#xff0c;在《从HelloWorld到WPF World》中&#xff0c;我们对WPF有了个大概的了解&am…

PostGIS容器运行

2019独角兽企业重金招聘Python工程师标准>>> 获取镜像&#xff1a; docker pull mdillon/postgis 该 mdillon/postgis 镜像提供了容器中运行Postgres&#xff08;内置安装PostGIS 2.5&#xff09; 。该镜像基于官方 postgres image&#xff0c;提供了多种变体&#…

小型数据库_如果您从事“小型科学”工作,那么您是否正在利用数据存储库?

小型数据库If you’re a scientist, especially one performing a lot of your research alone, you probably have more than one spreadsheet of important data that you just haven’t gotten around to writing up yet. Maybe you never will. Sitting idle on a hard dri…

BitmapEffect位图效果是简单的像素处理操作。它可以呈现下面几种特殊效果。

BitmapEffect位图效果是简单的像素处理操作。它可以呈现下面几种特殊效果。 BevelBitmapEffect 凹凸效果 BlurBitmapEffect 模糊效果 DropShadowBitmapEffect投影效果 EmbossBitmapEffect 浮雕效果 Outer…

AutoScaling 与函数计算结合,赋予更丰富的弹性能力

目前&#xff0c;弹性伸缩服务已经接入了负载均衡&#xff08;SLB&#xff09;、云数据库RDS 等云产品&#xff0c;但是暂未接入 云数据库Redis&#xff0c;有时候我们可能会需要弹性伸缩服务在扩缩容的时候自动将扩缩容涉及到的 ECS 实例私网 IP 添加到 Redis 白名单或者从 Re…

参考文献_参考

参考文献Recently, I am attracted by the news that Tanzania has attained lower middle income status under the World Bank’s classification, five years ahead of projection. Being curious on how they make the judgement, I take a look of the World Bank’s offi…

数据统计 测试方法_统计测试:了解如何为数据选择最佳测试!

数据统计 测试方法This post is not meant for seasoned statisticians. This is geared towards data scientists and machine learning (ML) learners & practitioners, who like me, do not come from a statistical background.Ť他的职位是不是意味着经验丰富的统计人…

spring的几个通知(前置、后置、环绕、异常、最终)

1、没有异常的 2、有异常的 1、被代理类接口Person.java 1 package com.xiaostudy;2 3 /**4 * desc 被代理类接口5 * 6 * author xiaostudy7 *8 */9 public interface Person { 10 11 public void add(); 12 public void update(); 13 public void delete();…

每个Power BI开发人员的Power Query提示

If someone asks you to define the Power Query, what should you say? If you’ve ever worked with Power BI, there is no chance that you haven’t used Power Query, even if you weren’t aware of it. Therefore, one could easily say that Power Query is the “he…

c# PDF 转换成图片

1.新建项目 2.新增一个新文件夹“lib”&#xff08;主要是为了存放引用的dll&#xff09; 3.将“gsdll32.dll 、PDFLibNet.dll 、PDFView.dll”3个dll添加到文件夹中 4.项目添加“PDFLibNet.dll 、PDFView.dll”2个类库的引用&#xff0c;并将gsdll32.dll 拷贝到项目生产根…