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,一经查实,立即删除!

相关文章

【数据库的备份与还原】 .

差异备份,日志备份还原 IF DB_ID(db) IS NOT NULL DROP DATABASE db GO CREATE DATABASE db GO CREATE TABLE db.dbo.T(ID INT PRIMARY KEY IDENTITY(1,1)); GO BACKUP DATABASE db TO DISKd:/1.bak WITH FORMAT GO INSERT INTO db.dbo.T DEFAULT VALUES GO BACKUP DATAB…

方法 数组

方法的特点: 定义方法可以将功能代码进行封装 封装:两方面含义: 1.将有特定逻辑的多条代码组合成一个整体!! 2.方便维护,提高代码的复用性(联想变量的作用域问题) 方法只有被调用才会被执行!!(方法调用的流程) 方法的重载: 两同一不同: 同类,同方法名 形参列表不同 …

java 控制jsp_JSP学习之Java Web中的安全控制实例详解

普通用户界面修改登录的Servlet,修改后的代码如下:LoginProcess.java代码:package servlet;import javabean.User;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.RequestDispatcher;import javax.servlet.Ser…

PHP 基础 自动类型转换之比较运算符

<?php var_dump( 123fg456>122); var_dump(some string 0); var_dump(123.0 123d456); var_dump(0 "a"); var_dump("1" "01"); var_dump("1" "1e0"); 当数字与字符串进行比较运算时&#xff0c;字符串会自动转…

java的多线程访问共享变量_java多线程通信之共享变量

(1)当访问共同的代码的时候&#xff1a;可以使用同一个Runnable对象&#xff0c;这个Runnable对象中有这个共享数据&#xff0c;比如卖票系统就可以这么做。或者这个共享数据封装在一个对象当中&#xff0c;然后对这个对象加锁&#xff0c;也可以实现数据安全访问。public clas…

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

2019独角兽企业重金招聘Python工程师标准>>> NoSQL一词最早出现在1998年。2009年Last.fm的Johan Oskarsson发起了一次关于分布式开源数据库的讨论&#xff0c;来自Rackspace的Eric Evans再次提出了NoSQL概念&#xff0c;这时的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 &#xff0c;这是我们…

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

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

DotNetBar office2007效果

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

Spring boot 中pom.xml 各个节点详解

<project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd "> <!-- 父项目的坐…

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 …

stack 的一些用法

#include<bits/stdc.h> using namespace std; int32_t main() {stack<int> st;st.push(1);st.push(2);st.push(3);cout<<st.size()<<endl;while(!st.empty()){cout<<st.top()<<endl;st.pop();} } 转载于:https://www.cnblogs.com/Andromed…

IS环境下配置PHP5+MySql+PHPMyAdmin

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

js复制功能

<div id"cardList"><div class"btn" onClick"copy(111)">点击我&#xff0c;复制我</div></div> <script type"text/javascript"> function copy(str){var save function (e){e.clipboardData.setDa…

input在iOS里的兼容性

input框在iOS里&#xff0c;无法聚焦&#xff0c;不能输入内容&#xff0c;把-webkit-user-select:none改成-webkit-user-select:auto;或者直接加一个style“-webkit-user-select:auto”.

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…

java用接口实例化对象_[求助]迷茫中,接口可以直接实例化对象吗?

可能是我没有写完整吧,还是我没有理解好1 接口public interface SetAndGetWeight{public void setW(double weight);public double getW();}2 类class Train{SetAndGetWeight[] things;public void Train(SetAndGetWeight[] things){this.thingsthings;}public void returnTota…

异常作业2(2018.08.22)

2、编写程序接收用户输入分数信息&#xff0c;如果分数在0—100之间&#xff0c; 输出成绩。如果成绩不在该范围内&#xff0c; 抛出异常信息&#xff0c;提示分数必须在0—100之间。 要求&#xff1a;使用自定义异常实现1 import java.util.Scanner;2 3 class AtException ext…

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

深度学习数据集中数据差异大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#图片处理基本应用(裁剪,缩放,清晰度,水印)

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