機器學習初學者:Matplotlib——面向對象接口的介紹

我為嵌入式平臺編寫應用程序。我的一個應用程序部署在一個網絡中,它從幾個網絡節點接收數據並處理它們。我的應用程序應該能夠在指定的時間內處理來自所有節點的數據。這是一個嚴格的約束。我依靠

matplotlib和pandas來可視化/分析收到的每個網絡數據包的時間分析信息。

機器學習初學者:Matplotlib——面向對象接口的介紹

上圖是每個接收到的數據包的處理時間的直方圖。這是使用matplotlib生成的。這個實驗有近20萬個數據點。這張圖告訴我一些重要的事情。它告訴我,大多數情況下,網絡數據包在到達後的30毫秒內得到處理。它還告訴我有兩個峰值,一個在10毫秒,另一個在大約20毫秒。您可以看到可視化在這裡非常重要,matplotlib可以很好地完成工作。

matplotlib是龐大的。這是一個非常有用的繪圖工具,但有時它可能會令人困惑。我第一次使用它時感到很困惑。matplotlib為繪圖提供了兩個不同的接口,我們可以使用這兩個接口中的任何一個來實現結果。這是我困惑的主要原因。每當我在網上搜索任何幫助時,我發現至少有兩種不同的方式。那時我決定深入挖掘它的接口,本教程就是這樣的結果。

本教程的重點是狹義的 - 理解“面向對象的接口”。我們不會從大型數據集開始。這樣做會將焦點轉移到數據集本身而不是matplotlib對象。大多數時候,我們將處理非常簡單的數據,就像數字列表一樣簡單。最後,我們將研究更大的數據集,以瞭解matplotlib如何用於分析更大的數據集。

Matplotlib接口

matplotlib提供兩個用於繪圖的接口

  • 使用pyplot進行MATLAB樣式繪圖
  • 面向對象的接口

在我研究matplotlib之後,我決定使用它的“面向對象的接口”。我發現它更容易使用。每個圖形都分為一些對象,對象層次結構清晰。我們通過研究對象來獲得結果。所以我將在本教程中重點介紹面向對象的接口。在方便使用它們的任何地方也會使用一些pyplot函數。

Matplotlib面向對象的接口

matplotlib中的圖分為兩個不同的對象。

  • 對象
  • 座標軸對象

圖對象可以包含一個或多個軸的對象。一個軸代表圖中的一個圖。在本教程中,我們將直接使用axis對象進行各種繪圖。

圖對象

import matplotlib.pyplot as plt
fig = plt.figure()
print(type(fig))

<class>

上面代碼片段的輸出是matplotlib.figure.Figureplt.figure()返回一個Figure對象。python中的type()方法用於查找對象的類型。所以我們此時有一個空的Figure對象。讓我們嘗試繪製它。

# Give the figure a title
fig.suptitle("Empty figure")
plt.show()

執行上面的代碼返回一個空圖。如下:

機器學習初學者:Matplotlib——面向對象接口的介紹

座標軸對象

我們需要一個或多個軸對象來開始繪圖。可以通過多種方式獲得座標軸軸對象。我們將從add_subplot()方法開始,稍後將探索其他方法。

ax = fig.add_subplot(1,1,1)
# Set the title of plot
ax.set_title("Empty plot")
plt.show()

add_subplot(num_rows,num_cols,subplot_location)方法創建一個大小為(num_rows x num_cols)的子圖的網格並在subplot_location返回子圖的座標軸對象。子圖以下列方式編號:

  • 第一個子圖位於(第一行,第一列)位置。從這個位置開始並繼續編號直到第一行的最後一列
  • 從第二行的最左側位置開始並繼續編號
  • 例:2x2子圖的網格中的第3個子圖位於=(第2行,第1列)

因此add_subplot(1,1,1)返回1x1子圖中網格中第一個位置的軸對象。換句話說,在圖中僅生成一個圖。執行上面的代碼給出了一個帶有xy軸的空圖,如下所示。

機器學習初學者:Matplotlib——面向對象接口的介紹

讓我們再舉一個例子。我們將圖形劃分為2x2子圖的網格,並獲得所有子圖的軸對象。

import matplotlib.pyplot as plt
fig = plt.figure()
# Generate a grid of 2x2 subplots and get
# axes object for 1st location

ax1 = fig.add_subplot(2,2,1)
ax1.set_title('First Location')
# Get the axes object for subplot at 2nd
# location
ax2 = fig.add_subplot(2,2,2)
ax2.set_title('Second Location')
# Get the axes object for subplot at 3rd
# location
ax3 = fig.add_subplot(2,2,3)
ax3.set_xlabel('Third Location')
# Get the axes object for subplot at 4th
# location
ax4 = fig.add_subplot(2,2,4)
ax4.set_xlabel('Fourth Location')
# Display
plt.show()
機器學習初學者:Matplotlib——面向對象接口的介紹

上面代碼的輸出得到:

機器學習初學者:Matplotlib——面向對象接口的介紹

2x2子圖的網格

一旦我們得到的座標軸對象,我們可以調用座標軸對象的方法生成圖形。我們將在示例中使用以下座標軸對象方法:

  • plot(x,y):生成y-x圖
  • set_xlabel():X軸的標籤
  • set_ylabel():Y軸的標籤
  • set_title():圖的標題
  • legend():為圖形生成圖例
  • hist():生成直方圖
  • scatter():生成散點圖

有關座標軸類的更多詳細信息,請參閱matplotlib axes類頁面。https://matplotlib.org/api/axes_api.html

例1:簡單的XY圖

我們可以使用座標軸對象的plot()方法繪製數據。這在以下示例中進行了演示。

import matplotlib.pyplot as plt
# Generate data for plots
x = [1, 2, 3, 4, 5]
y = x
# Get an empty figure
fig1 = plt.figure()
# Get the axes instance at 1st location in 1x1 grid
ax = fig1.add_subplot(1,1,1)

# Generate the plot
ax.plot(x, y)
# Set labels for x and y axis
ax.set_xlabel('X--->')
ax.set_ylabel('Y--->')
# Set title for the plot
ax.set_title('Simple XY plot')
# Display the figure
plt.show()
機器學習初學者:Matplotlib——面向對象接口的介紹

執行上面的代碼將生成y = x plot,如下所示

機器學習初學者:Matplotlib——面向對象接口的介紹

例2:同一圖中的多個圖

讓我們嘗試在單個繪圖窗口中生成2個圖形。一個是y = x而另一個是z =x²

import matplotlib.pyplot as plt
# Function to get the square of each element in the list
def list_square(a_list):
return [element**2 for element in a_list]
# Multiple plot in same subplot window
# plot y = x and z = x^2 in the same subplot window
fig2 = plt.figure()
x = [1, 2, 3, 4, 5]
y = x
z = list_square(x)
# Get the axes instance
ax = fig2.add_subplot(1,1,1)
# Plot y vs x as well as z vs x. label will be used by ax.legend() method to generate a legend automatically
ax.plot(x, y, label='y')
ax.plot(x, z, label='z')
ax.set_xlabel("X------>")
# Generate legend
ax.legend()
# Set title
ax.set_title('Two plots one axes')
# Display
plt.show()
機器學習初學者:Matplotlib——面向對象接口的介紹

這次使用一個額外的參數 - label來調用ax.plot()。這是為圖表設置標籤。ax.legend()方法使用此標籤生成繪圖的圖例。上面代碼的輸出如下所示:

機器學習初學者:Matplotlib——面向對象接口的介紹

如您所見,在一個繪圖窗口中生成了兩個圖形。在左上角生成了另一個圖例。

例3:圖中的兩個圖

我們現在將在圖中生成多個圖

import matplotlib.pyplot as plt
# Function to get the square of each element in the list
def list_square(a_list):
return [element**2 for element in a_list]
# Multiple subplots in same figure
fig3 = plt.figure()
x = [1, 2, 3, 4, 5]
y = x
z = list_square(x)
# Divide the figure into 1 row 2 column grid and get the
# axes object for the first column
ax1 = fig3.add_subplot(1,2,1)
# plot y = x on axes instance 1
ax1.plot(x, y)
# set x and y axis labels
ax1.set_xlabel('X------>')
ax1.set_ylabel('Y------>')
ax1.set_title('y=x plot')
# Get second axes instance in the second column of the 1x2 grid
ax2 = fig3.add_subplot(1,2,2)
# plot z = x^2
ax2.plot(x, z)
ax2.set_xlabel('X---------->')
ax2.set_ylabel('z=X^2--------->')
ax2.set_title('z=x^2 plot')
# Generate the title for the Figure. Note that this is different then the title for individual plots
plt.suptitle("Two plots in a figure")
plt.show()
機器學習初學者:Matplotlib——面向對象接口的介紹

執行上面的代碼會生成下圖:

機器學習初學者:Matplotlib——面向對象接口的介紹

Ex3:直方圖

直方圖可用於可視化數據的基礎分佈。以下是直方圖的示例。使用numpy生成此示例的數據。從高斯分佈產生1000個樣本,平均值為10,標準偏差為0.5。

# coding: utf-8
import matplotlib.pyplot as plt
import numpy as np
# Generate 1000 numbers from gaussian sample

mean = 10
std = 0.5
num_samples = 1000
samples = np.random.normal(mean, std, num_samples)
# Get an instance of Figure object
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
# Generate histogram plot
ax.hist(samples)
ax.set_xlabel('Sample values')
ax.set_ylabel('Frequency')
ax.set_title('Histogram plot')
plt.show()
機器學習初學者:Matplotlib——面向對象接口的介紹

機器學習初學者:Matplotlib——面向對象接口的介紹

上圖中的x軸為樣本值,y軸是每個樣本的頻率。我們可以在10處觀察到值一個峰值。

根據3 sigma規則,99.7%的高斯分佈樣本位於均值的三個標準偏差範圍內。對於本例,此範圍為[8.5,11.5]。這也可以從上面的圖中驗證。

在更大的數據集上繪圖

在這個例子中,我們將使用“California Housing Price Dataset”。

數據集中的每一行都包含一個塊的數據。塊可以被認為是小的區域。數據集包含以下列:

  • 經度 - 經度
  • 緯度 - 緯度(以度為單位)
  • housing_median_age - 街區內房屋的平均年齡
  • total_rooms - 街區的房間總數
  • total_bedrooms - 街區的臥室總數
  • population - 街區的人口
  • households - 住戶的總數,住在一個住宅單元內的一組住戶
  • median_income - 一個街區家庭的平均收入
  • median_house_value - 街區內住戶的平均房屋價值
  • ocean_proximity - 海景房屋的位置

讓我們生成一些圖來學習有關數據集的某些內容。

  1. “median_house_value”的分佈
  2. 分配“median_income”
  3. 我的常識告訴我,在收入高的地方,房屋應該是昂貴的,反之亦然。在人口較多的地方,一個街區的房間數量應該更多。讓我們試著通過生成一些圖來弄清楚這一點。

Pyplot subplots()方法 - 我們將在此示例中使用pyplot子圖方法來獲取座標軸對象。 我們已經看到add_subplot()方法一次只返回一個座標軸對象。因此需要為圖中的每個子圖調用add_subplot()方法。pyplot subplots () API解決了這個問題。它返回一個numpy nd數組的軸對象。使用座標軸對象生成繪圖與前面示例中解釋的相同。

import matplotlib.pyplot as plt 
import pandas as pd
import numpy as np
# Read the csv file into a pandas dataframe
# A dataframe is basically a table of data.

df_housing = pd.read_csv("housing.csv")
# Get figure object and an array of axes objects
fig, arr_ax = plt.subplots(2, 2)
# Histogram - median_house_value
arr_ax[0,0].hist(df_housing['median_house_value'])
arr_ax[0,0].set_title('median_house_value')
# Histogram - median_income
arr_ax[0,1].hist(df_housing['median_income'])
arr_ax[0,1].set_title('median_income')
# Scatter - population vs total_rooms
arr_ax[1,0].scatter(df_housing['population'], df_housing['total_rooms'])
arr_ax[1,0].set_xlabel('population')
arr_ax[1,0].set_ylabel('total_rooms')
# scatter - median_income vs median_house_value
arr_ax[1,1].scatter(df_housing['median_income'], df_housing['median_house_value'])
arr_ax[1,1].set_xlabel('median_income')
arr_ax[1,1].set_ylabel('median_house_value')
plt.show()
print('DONE : Matplotlib california housing dataset plotting')
機器學習初學者:Matplotlib——面向對象接口的介紹

我使用python pandas庫來讀取數據集中的數據。數據集是名為“housing.csv”的csv文件。

plt.subplots(2,2)返回一個圖形對象和一個大小為2x2的座標軸對象的2D數組。可以通過對座標軸對象的二維數組建立索引來訪問各個子圖的座標軸對象。

機器學習初學者:Matplotlib——面向對象接口的介紹

第一個圖有一個很好的高斯分佈,除了最後。該圖告訴我們,“median_house_value”的平均值介於1,00,000到2,00,000美元之間。上限為5,00,000美元。還有驚人的大量房屋售價約為5,00,000美元。

第二個圖也有很好的分佈。它告訴我們,平均收入介於20,000到40,000美元之間。收入超過80,000美元的人也很少。

第三個圖證實了,在人口較多的地方,房間數量更多。

第四個圖證實了我們的常識,即“median_house_value”應該更多地位於“median_income”更多的地方,反之亦然。

這只是一個例子。可以對此數據集進行更多分析,但這超出了本教程的範圍。

結論

我已經提供了matplotlib的面向對象接口的介紹。本教程的重點是解釋圖和座標軸對象及其關係。


分享到:


相關文章: