一文搞定Matplotlib 各個示例丨建議收藏


摘要:Matplotlib 是 Python 的繪圖庫。 它可與 NumPy 一起使用 ,Matplotlib也是深度學習的常用繪圖庫,主要是將訓練的成果進行圖形化,因為這樣更直觀,更方便發現訓練中的問題。

本文分享自華為雲社區《深度學習基礎之matplotlib,一文搞定各個示例,建議收藏以后參考丨【百變AI秀】》,作者:香菜聊游戲。

Matplotlib 是 Python 的繪圖庫。 它可與 NumPy 一起使用 ,Matplotlib也是深度學習的常用繪圖庫,主要是將訓練的成果進行圖形化,因為這樣更直觀,更方便發現訓練中的問題,今天來學習下,走起!!

1、先來個demo 分析下

下面是一個典型的圖形,我們如果想畫這樣一個圖,應該做什么,應該准備哪些數據,這樣的圖形有哪些屬性是你需要關注的?

1、怎么做一個圖? 怎么創建一個畫板?

2、怎么設置數據?x,y 的數據怎么放上去

3、設置圖標示,左上角的各種線的顏色這種小窗體怎么畫上去?

4、外觀 ,不同線的顏色不同怎么處理?

5、怎么顯示?

6、怎么保存?

這么多的問題,怎么搞?一步一步來,先給你看看代碼,看下能明白多少

x = np.linspace(0, 2, 100)

plt.plot(x, x, label='linear')  # Plot some data on the (implicit) axes.
plt.plot(x, x**2, label='quadratic')  # etc.
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()

2、matplotlib中的概念

下面這張圖是官網的一張圖,指明了很多概念,基本上常用的我們都能看到,看起來大部分也都能理解

Figure(容器)

整個圖像稱為Figure, Figure用於保存返回的Axes(坐標域), 一個Figure可以包含任意數量的Axes,可以理解為一個容器。

Axes(坐標域)

可以將它理解為一個單個畫板, 一個Axes包含兩個Axis(坐標軸)(在3D圖中為三個Axis), 每個Axes都有 一個 title(方法: set_title()), 一個x-label(方法: set_xlabel()), 一個y-label(方法: set_ylabel()).注意:一個給出的Axes對象只能包含在一個Figure中。

Axis(坐標軸)

這是一種類似數軸的對象。可以通過Axis以及Axis的方法設置坐標軸上刻度的樣式和坐標軸上的值。刻度的位置由Locater對象決定, 刻度對應的值由Formatter對象決定。

總結:Axes 差不多就是我們腦中所想的一個 ‘plot’。可以說就是單張紙。一個確定的figure當中可以有很多個Axes,但是一個確定的Axes只能在一個figure當中。

2維空間的Axes包含兩個Axis(即x軸與y軸),3維空間的Axes包含三個Axis(即x軸,y軸和z軸)。這里注意區別Axes和Axis的概念。

Axis是一個數軸對象,它主要用於設置一個Axes里面的數據約束(即兩個端點的值)和軸上的ticks(就是軸上的標記刻度)和tick-labels刻度的標簽。

Subplot:子圖,figure對象下創建一個或多個subplot對象(即axes)用於繪制圖像。

axes: 設置坐標軸邊界和表面的顏色、坐標刻度值大小和網格的顯示
figure: 控制dpi、邊界顏色、圖形大小、和子區( subplot)設置
font: 字體集(font family)、字體大小和樣式設置
grid: 設置網格顏色和線性
legend: 設置圖例和其中的文本的顯示
line: 設置線條(顏色、線型、寬度等)和標記
patch: 是填充2D空間的圖形對象,如多邊形和圓。控制線寬、顏色和抗鋸齒設置等。
savefig: 可以對保存的圖形進行單獨設置。例如,設置渲染的文件的背景為白色。
verbose: 設置matplotlib在執行期間信息輸出,如silent、helpful、debug和debug-annoying。
xticks和yticks: 為x,y軸的主刻度和次刻度設置顏色、大小、方向,以及標簽大小。

3、matplotlib 支持的圖形

3.1 線圖line

import matplotlib.pyplot as plt
import numpy as np

# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()

fig.savefig("test.png")
plt.show()

3.2 直方圖hist

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(19680801)

# example data
mu = 100  # mean of distribution
sigma = 15  # standard deviation of distribution
x = mu + sigma * np.random.randn(437)

num_bins = 50

fig, ax = plt.subplots()

# the histogram of the data
n, bins, patches = ax.hist(x, num_bins, density=True)

# add a 'best fit' line
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
     np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
ax.plot(bins, y, '--')
ax.set_xlabel('Smarts')
ax.set_ylabel('Probability density')
ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

# Tweak spacing to prevent clipping of ylabel
fig.tight_layout()
plt.show()

3.3 路線

import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

Path = mpath.Path
path_data = [
    (Path.MOVETO, (1.58, -2.57)),
    (Path.CURVE4, (0.35, -1.1)),
    (Path.CURVE4, (-1.75, 2.0)),
    (Path.CURVE4, (0.375, 2.0)),
    (Path.LINETO, (0.85, 1.15)),
    (Path.CURVE4, (2.2, 3.2)),
    (Path.CURVE4, (3, 0.05)),
    (Path.CURVE4, (2.0, -0.5)),
    (Path.CLOSEPOLY, (1.58, -2.57)),
    ]
codes, verts = zip(*path_data)
path = mpath.Path(verts, codes)
patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5)
ax.add_patch(patch)

# plot control points and connecting lines
x, y = zip(*path.vertices)
line, = ax.plot(x, y, 'go-')

ax.grid()
ax.axis('equal')
plt.show()

3.4 散點圖Scatter

3.5 極坐標圖Polar plots

import numpy as np
import matplotlib.pyplot as plt
r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r

fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
ax.plot(theta, r)
ax.set_rmax(2)
ax.set_rticks([0.5, 1, 1.5, 2])  # Less radial ticks
ax.set_rlabel_position(-22.5)  # Move radial labels away from plotted line
ax.grid(True)

ax.set_title("A line plot on a polar axis", va='bottom')
plt.show()

3.6 餅圖pie

import matplotlib.pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

3.7 3d 圖形

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import numpy as np

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})

# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)

# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
# A StrMethodFormatter is used automatically
ax.zaxis.set_major_formatter('{x:.02f}')

# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()
#使用numpy產生數據
x=np.arange(-5,5,0.1)
y=x*3

#創建窗口、子圖
#方法1:先創建窗口,再創建子圖。(一定繪制)
fig = plt.figure(num=1, figsize=(15, 8),dpi=80)     #開啟一個窗口,同時設置大小,分辨率
ax1 = fig.add_subplot(2,1,1)  #通過fig添加子圖,參數:行數,列數,第幾個。
ax2 = fig.add_subplot(2,1,2)  #通過fig添加子圖,參數:行數,列數,第幾個。
print(fig,ax1,ax2)
#方法2:一次性創建窗口和多個子圖。(空白不繪制)
fig,axarr = plt.subplots(4,1)  #開一個新窗口,並添加4個子圖,返回子圖數組
ax1 = axarr[0]    #通過子圖數組獲取一個子圖
print(fig,ax1)
#方法3:一次性創建窗口和一個子圖。(空白不繪制)
ax1 = plt.subplot(1,1,1,facecolor='white')      #開一個新窗口,創建1個子圖。facecolor設置背景顏色
print(ax1)
#獲取對窗口的引用,適用於上面三種方法
# fig = plt.gcf()   #獲得當前figure
# fig=ax1.figure   #獲得指定子圖所屬窗口

# fig.subplots_adjust(left=0)                         #設置窗口左內邊距為0,即左邊留白為0。

#設置子圖的基本元素
ax1.set_title('python-drawing')            #設置圖體,plt.title
ax1.set_xlabel('x-name')                    #設置x軸名稱,plt.xlabel
ax1.set_ylabel('y-name')                    #設置y軸名稱,plt.ylabel
plt.axis([-6,6,-10,10])                  #設置橫縱坐標軸范圍,這個在子圖中被分解為下面兩個函數
ax1.set_xlim(-5,5)                           #設置橫軸范圍,會覆蓋上面的橫坐標,plt.xlim
ax1.set_ylim(-10,10)                         #設置縱軸范圍,會覆蓋上面的縱坐標,plt.ylim

xmajorLocator = MultipleLocator(2)   #定義橫向主刻度標簽的刻度差為2的倍數。就是隔幾個刻度才顯示一個標簽文本
ymajorLocator = MultipleLocator(3)   #定義縱向主刻度標簽的刻度差為3的倍數。就是隔幾個刻度才顯示一個標簽文本

ax1.xaxis.set_major_locator(xmajorLocator) #x軸 應用定義的橫向主刻度格式。如果不應用將采用默認刻度格式
ax1.yaxis.set_major_locator(ymajorLocator) #y軸 應用定義的縱向主刻度格式。如果不應用將采用默認刻度格式

ax1.xaxis.grid(True, which='major')      #x坐標軸的網格使用定義的主刻度格式
ax1.yaxis.grid(True, which='major')      #x坐標軸的網格使用定義的主刻度格式

ax1.set_xticks([])     #去除坐標軸刻度
ax1.set_xticks((-5,-3,-1,1,3,5))  #設置坐標軸刻度
ax1.set_xticklabels(labels=['x1','x2','x3','x4','x5'],rotation=-30,fontsize='small')  #設置刻度的顯示文本,rotation旋轉角度,fontsize字體大小

plot1=ax1.plot(x,y,marker='o',color='g',label='legend1')   #點圖:marker圖標
plot2=ax1.plot(x,y,linestyle='--',alpha=0.5,color='r',label='legend2')   #線圖:linestyle線性,alpha透明度,color顏色,label圖例文本

ax1.legend(loc='upper left')            #顯示圖例,plt.legend()
ax1.text(2.8, 7, r'y=3*x')                #指定位置顯示文字,plt.text()
ax1.annotate('important point', xy=(2, 6), xytext=(3, 1.5),  #添加標注,參數:注釋文本、指向點、文字位置、箭頭屬性
            arrowprops=dict(facecolor='black', shrink=0.05),
            )
#顯示網格。which參數的值為major(只繪制大刻度)、minor(只繪制小刻度)、both,默認值為major。axis為'x','y','both'
ax1.grid(b=True,which='major',axis='both',alpha= 0.5,color='skyblue',linestyle='--',linewidth=2)

axes1 = plt.axes([.2, .3, .1, .1], facecolor='y')       #在當前窗口添加一個子圖,rect=[左, 下, 寬, 高],是使用的絕對布局,不和以存在窗口擠占空間
axes1.plot(x,y)  #在子圖上畫圖
plt.savefig('aa.jpg',dpi=400,bbox_inches='tight')   #savefig保存圖片,dpi分辨率,bbox_inches子圖周邊白色空間的大小
plt.show()    #打開窗口,對於方法1創建在窗口一定繪制,對於方法2方法3創建的窗口,若坐標系全部空白,則不繪制

總結:

上面大部分的數據是總結自官方網站:https://matplotlib.org/stable/tutorials/introductory/usage.html#sphx-glr-tutorials-introductory-usage-py

如果上面有說的不准確的可以參考官方網站,還不能完全掌握,我也只能畫畫簡單的圖,能滿足日常的需求罷了。

 

點擊關注,第一時間了解華為雲新鮮技術~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM