日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

matplotlib基礎知識

作者:bujbujbiu 更新時間: 2022-08-15 編程語言

(一)基礎知識

1.基礎用法(figure,plot,show)

  • plt.figure:定義一個figure圖像窗口,可以有很多小圖片
  • plt.plot:繪制曲線
  • plt.show:顯示圖像
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 2*x + 1
y2 = x**2
plt.figure(num=3,figsize=(8,5)) # 定義一個figure圖像窗口,編號為3;大小為(8, 5)
plt.plot(x,y2)
# color曲線顏色:紅,linewidth曲線寬度:1.0,linestyle曲線類型:虛線
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.show()

在這里插入圖片描述

2.調整軸的刻度范圍和名稱(xlim,xlabel,xticks)

  • plt.xlim:設置x軸范圍
  • plt.xlabel:設置x軸名稱
  • plt.xticks:設置x軸刻度及名稱
plt.xlim((-1,2)) # 設置x軸范圍(-1,2)
plt.ylim((-2,3)) # 設置y軸范圍(-2,3)
plt.xlabel('x') # 設置x軸名稱
plt.ylabel('y') # 設置y軸名稱
new_ticks = np.linspace(-1,2,5) # 5個[-1,2]之間均勻分布的數
plt.xticks(new_ticks)
# 設置y軸刻度及名稱,刻度為[-2, -1.8, -1, 1.22, 3];對應刻度的名稱為[‘really bad’,’bad’,’normal’,’good’, ‘really good’]
plt.yticks([-2,-1.8,-1,1.22,3],[r'$really\ bad$',r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
plt.show()

在這里插入圖片描述

3.調整坐標軸至原點

(1)設置邊框顏色白色

  • plt.gca:獲取坐標軸信息
  • ax.spines:選擇邊框
  • set_color:設置顏色
ax = plt.gca() # 獲取當前坐標軸信息
ax.spines['right'].set_color('none') # spines設置邊框,選擇right右邊框,set_color設置邊框顏色,默認白色
ax.spines['top'].set_color('none') # spines設置邊框,選擇top上邊框,set_color設置邊框顏色,默認白色 

(2)調整坐標軸位置(0,0)中心

  • ax.xaxis.set_ticks_position:設置x軸刻度數字/名稱的位置
  • set_position:設置邊框位置
# 設置x軸刻度數字/名稱的位置為bottom(可選top,bottom,both,default,none)
ax.xaxis.set_ticks_position('bottom') 
# 使用.spines選擇底部邊框(x軸),使用.set_position設置邊框(x軸)位置在y=0處
# 位置屬性可選(outward,axes,data)
ax.spines['bottom'].set_position(('data',0))
# 設置y軸刻度數字/名稱的位置為left
ax.yaxis.set_ticks_position('left')
# 使用.spines選擇左邊邊框(y軸),使用.set_position設置邊框(y軸)位置在x=0處
ax.spines['left'].set_position(('data',0))
plt.show()

在這里插入圖片描述

4.顯示數據對應的圖像名稱

  • plt.legend:顯示數據名稱

將上文中plot代碼更改為

plt.plot(x,y2,label='square line')
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--',label='linear line')

添加如下代碼

plt.legend(loc='upper right')

下圖中的右上角顯示了每個圖的名稱
在這里插入圖片描述
如果想修改label,除了在plot中修改以外,可以先將圖像用變量存儲起來

l2, = plt.plot(x,y2,label='square line')
l1, = plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--',label='linear line')
plt.legend(handles=[l1,l2],labels=['up','down'],loc='best')

在這里插入圖片描述
loc參數表示圖像名稱的顯示位置,best表示自動分配最佳位置

 'best' : 0,          
 'upper right'  : 1,
 'upper left'   : 2,
 'lower left'   : 3,
 'lower right'  : 4,
 'right'        : 5,
 'center left'  : 6,
 'center right' : 7,
 'lower center' : 8,
 'upper center' : 9,
 'center'       : 10,

5.添加標注(箭頭和文本)

  • plt.annotate:指向型注釋,標注不僅包含注釋的文本內容還包含箭頭指向
  • plt.text:文本型注釋

首先繪制一條直線

x = np.linspace(-3,3,50)
y = 2*x + 1

plt.figure(num=1,figsize=(8,5))
plt.plot(x,y)

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))

ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

標注點(1,3)的位置信息,繪制一條垂直于x軸的虛線,繪制一個點

x0 = 1
y0 = 3
plt.plot([x0,x0],[0,y0],'k--',linewidth=2.5)
plt.scatter([x0,],[y0,],s=50,color='b')

添加箭頭標注

# xycoords='data'基于數據的值來選位置
# xytext=(+30, -30) 和 textcoords='offset points' 對于標注位置的描述和xy偏差值
# arrowprops是對圖中箭頭類型的一些設置
plt.annotate(r'$2x+1=%s$'%y0,xy=(x0,y0),xycoords='data',xytext=(+30,-30),textcoords='offset points',
            fontsize=16,arrowprops=dict(arrowstyle='->',connectionstyle="arc3,rad=.2"))

添加注釋文本

# -3.7,3是text的位置,空格需要轉字符\,fontdict設置文本字體大小和顏色
plt.text(-3.7,3,r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
        fontdict={'size':16,'color':'r'})

在這里插入圖片描述

(二)畫圖

散點圖scatter

# 生成1024個呈標準正態分布的二維數據組 (平均數是0,方差為1) 作為一個數據集
n = 1024
x = np.random.normal(0,1,n)
y = np.random.normal(0,1,n)
t = np.arctan2(y,x) # 顏色

plt.scatter(x,y,s=75,c=t,alpha=0.5) # size=75,透明的alpha=50%
plt.xlim(-1.5,1.5)
plt.xticks(()) # 隱藏x軸的刻度
plt.ylim(-1.5,1.5)
plt.yticks(())
plt.show()

在這里插入圖片描述

柱狀圖

向上向下分別生成12個數據,X為 0 到 11 的整數 ,Y是相應的均勻分布的隨機數據

n = 12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)

繪制柱狀圖

plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')

plt.xlim(-.5, n)
#plt.xticks(())
plt.ylim(-1.25, 1.25)
#plt.yticks(())

添加文本,ha是橫向居中對齊,va縱向底部(頂部)對齊

for x, y in zip(X, Y1):
    # ha: horizontal alignment
    # va: vertical alignment
    plt.text(x + 0.1, y + 0.05, '%.2f' % y, ha='center', va='bottom')

for x, y in zip(X, Y2):
    plt.text(x + 0.1, -y - 0.05, '%.2f' % y, ha='center', va='top')

在這里插入圖片描述

等高線圖

# x, y 分別是在區間 [-3,3] 中均勻分布的256個值
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
# meshgrid在二維平面將每一個x和每一個y分別對應起來,編織成柵格
X,Y = np.meshgrid(x,y)

# 高度函數
def f(x,y):
    return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 - y**2)

# 使用函數plt.contourf進行顏色填充,位置參數分別為:X, Y, f(X,Y)
# 透明度0.75,并將 f(X,Y) 的值對應到color map的暖色組中尋找對應顏色
plt.contourf(X,Y,f(X,Y),8,alpha=.75,cmap=plt.cm.hot)
# 使用plt.contour繪制等高線,黑色線條,寬度0.5
c = plt.contour(X,Y,f(X,Y),8,color = 'black',linewidth = 0.5)

# inline控制是否將Label畫在線里面,字體大小為10
plt.clabel(c, inline=True, fontsize=10)
plt.xticks(())
plt.yticks(())

在這里插入圖片描述

2D圖

繪制2D圖像

#  3x3 的 2D-array 來表示點的顏色,每一個點就是一個pixel。
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
              0.365348418405, 0.439599930621, 0.525083754405,
              0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')

interpolation內插法,以下為matplotlib官網上對于內插法的不同方法的描述,此處選擇Nearest-neighbor 的方法
在這里插入圖片描述
添加注釋條

# shrink參數,使colorbar的長度變短為原來的92%:
plt.colorbar(shrink=0.92)
plt.xticks(())
plt.yticks(())
plt.show()

在這里插入圖片描述

3D圖

額外導入Axes3D顯示3D坐標

import matplotlib.pyplot as plt
import numpy as np

# 導入Axes3D(3D坐標顯示)
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig) # 在窗口上添加3D坐標軸
X = np.arange(-4,4,0.25)
Y = np.arange(-4,4,0.25)
X,Y = np.meshgrid(X,Y)
r = np.sqrt(X**2 + Y**2)
z = np.sin(r)
# rstride和cstride分別代表 row 和 column 的跨度
ax.plot_surface(X,Y,z,rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
# 投影,zdir決定投影方向
ax.contourf(X, Y, z, zdir='z',offset=-1.3, cmap=plt.get_cmap('rainbow'))

在這里插入圖片描述

(三) 多圖subplot

  • plt.subplot:將圖像窗口分成多個小窗口

多圖均勻分布

import matplotlib.pyplot as plt
plt.figure() # 新建一個圖像窗口

plt.subplot(2,2,1) # 將整個圖像窗口分為2行2列,當前位置為1
plt.plot([0,1],[1,0])
plt.subplot(2,2,2)
plt.bar([0,1,2],[2,3,1])
plt.subplot(223)
plt.plot(list(np.arange(5)))
plt.subplot(224)
plt.bar(list(np.arange(3)),[1,2,3])
plt.show()

在這里插入圖片描述

多圖不均勻分布

import matplotlib.pyplot as plt
plt.figure() # 新建一個圖像窗口

plt.subplot(2,1,1) # 將整個圖像窗口分為2行1列,當前位置為1
plt.plot([0,1],[1,0])
plt.subplot(2,3,4) # 將整個圖像窗口分為2行1列,當前位置為4,原先第1行列變成3列
plt.bar([0,1,2],[2,3,1])
plt.subplot(235)
plt.plot(list(np.arange(5)))
plt.subplot(236)
plt.bar(list(np.arange(3)),[1,2,3])
plt.show()

在這里插入圖片描述

圖中圖

一個大圖離有兩個小圖
在這里插入圖片描述
大圖繪制

fig = plt.figure()
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]

# 4個值都是大圖占整個figure坐標系的百分比
# 若figure大小為10*10,則大圖(1,1)為起點,高8,寬8
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8

# 將大圖坐標系添加到figure中
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x,y,'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('big')

小圖繪制,更改坐標系位置和大小即可,plt也可以繪制

ax2 = fig.add_axes([0.2, 0.6, 0.25, 0.25])
ax2.plot(x,y,'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('small 1')

plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1],x,'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title('small 2')

兩個y軸

x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 * y1

# 獲取figure默認的坐標系 ax1
fig,ax1 = plt.subplots()
# 對ax1調用twinx()方法,生成如同鏡面效果后的ax2
ax2 = ax1.twinx()

ax1.plot(x,y1,'g-')
ax1.set_xlabel('x data')
ax1.set_ylabel('y1 data',color='g')
ax2.plot(x,y2,'m')
ax2.set_ylabel('y2 data',color='m')
plt.show()

在這里插入圖片描述

(四) 動畫animation

具體參考matplotlib animation api

繪制0~2π內的正弦曲線的動態圖像

import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np

fig,ax = plt.subplots()
x = np.arange(0,2*np.pi,0.01)
def animate(i):
    line.set_ydata(np.sin(x + i/10.0))
    return line,

def init():
    line.set_ydata(np.sin(x))

調用FuncAnimation函數生成動畫,參數如下

  • fig :進行動畫繪制的figure
  • func :自定義動畫函數,即傳入剛定義的函數animate
  • frames :動畫長度,一次循環包含的幀數
  • init_func :自定義開始幀,即傳入剛定義的函數init
  • interval: 更新頻率,以ms計
  • blit: 選擇更新所有點,還是僅更新產生變化的點。應選擇True,mac用戶選擇False,否則無法顯示動畫
ani = animation.FuncAnimation(fig=fig,
                              func=animate,
                              frames=100,
                              init_func=init,
                              interval=20,
                              blit=False)
plt.show()

實為動圖
在這里插入圖片描述

(五)交互圖ion

神經網絡訓練時需要動態看到loss的變化
參考:https://blog.csdn.net/weixin_42990464/article/details/112347386

  • plt.ion():開啟交互模式
  • plt.ioff():關閉交互模式
  • plt.clf():清除當前figure
  • plt.cla():清除當前axes
  • plt.pause():暫停

注意show之前先用ioff關閉交互模式

import matplotlib.pyplot as plt
x = list(range(1, 21))  
loss = [2 / (i**2) for i in x]  

plt.ion()

def plot(ix,iy):
    plt.cla()
    plt.title("loss")
    plt.plot(ix, iy)
    plt.xlabel("epoch")
    plt.ylabel("loss")
    plt.pause(0.5)

for i in range(1, len(x)):
    ix = x[:i]
    iy = loss[:i]
    plot(ix,iy)

plt.ioff()
plt.show()

在這里插入圖片描述

原文鏈接:https://blog.csdn.net/weixin_45526117/article/details/125003200

欄目分類
最近更新