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.pswp.cn/news/388778.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388778.shtml
英文地址,請注明出處:http://en.pswp.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;大部分網站基本都是將原圖等比縮放來生成縮略圖。但完美主義者會發現一些問題&#…