Matplotlib.pyplot 常用方法

參考 https://www.cnblogs.com/shaosks/p/9849446.html

Matplotlib.pyplot 常用方法
  1、介紹
    Matplotlib 是一個 Python 的 2D繪圖庫,它以各種硬拷貝格式和跨平臺的交互式環境生成出版質量級別的圖形。通過 Matplotlib,開發者可以僅需要幾行代碼,便可以生成繪圖,

直方圖,功率譜,條形圖,錯誤圖,散點圖等。

2、Matplotlib基礎知識
    2.1、Matplotlib中的基本圖表包括的元素
    x軸和y軸
    水平和垂直的軸線
    x軸和y軸刻度
    刻度標示座標軸的分隔,包括最小刻度和最大刻度
    x軸和y軸刻度標籤
    表示特定座標軸的值
    繪圖區域
    實際繪圖的區域
   
   2.2、hold屬性
    hold屬性默認爲True,允許在一幅圖中繪製多個曲線;將hold屬性修改爲False,每一個plot都會覆蓋前面的plot。
    但是目前不推薦去動hold這個屬性,這種做法(會有警告)。因此使用默認設置即可。

2.3、網格線
    grid方法
    使用grid方法爲圖添加網格線
    設置grid參數(參數與plot函數相同)
    .lw代表linewidth,線的粗細
    .alpha表示線的明暗程度

2.4、axis方法
    如果axis方法沒有任何參數,則返回當前座標軸的上下限

2.5、xlim方法和ylim方法
    除了plt.axis方法,還可以通過xlim,ylim方法設置座標軸範圍

3、配置屬性
    Matplotlib.plt是面向對象的繪圖庫,可以爲每個對象配置它們的屬性,有三個方法:

對象的set_屬性名()
 對象的set()
 pylot模塊提供的setp()函數
    如下例子:

複製代碼
plt.figure()
line = plt.plot(range(5))[0] # plot函數返回的是一個列表,因爲可以同時畫多條線的哦;
line.set_color(‘r’)
line.set_linewidth(2.0)
plt.show()
####################################
plt.figure()
line = plt.plot(range(5))[0]         # plot函數返回的是一個列表,因爲可以同時畫多條線;
line.set(color = ‘g’,linewidth = 2.0)
plt.show()
####################################
plt.figure()
lines = plt.plot(range(5),range(5),range(5),range(8,13)) # plot函數返回一個列表;
plt.setp(lines, color = ‘g’,linewidth = 2.0) # setp函數可以對多條線進行設置的;
plt.show()
複製代碼
    獲取屬性:

一個是通過對象的方法get_屬性名()函數,
 一個是通過pylot模塊提供的getp()函數。
    getp()有兩個調用方法,一個是隻有要的查看的對象一個參數,一個是要查看的對象現屬性兩個參數;如:

getp(obj, property=None)

plt.getp(line)
plt.getp(line, ‘color’)

4、Artist 對象
    matplotlib API包含有三層:

backend_bases.FigureCanvas : 圖表的繪製領域
backend_bases.Renderer : 知道如何在FigureCanvas上如何繪圖
artist.Artist : 知道如何使用Renderer在FigureCanvas上繪圖
    FigureCanvas和Renderer需要處理底層的繪圖操作,例如使用wxPython在界面上繪圖,或者使用PostScript繪製PDF。Artist則處理所有的高層結構,例如處理圖表、

文字和曲線等的繪製和佈局。通常我們只和Artist打交道,而不需要關心底層的繪製細節。

Artists分爲簡單類型和容器類型兩種。簡單類型的Artists爲標準的繪圖元件,例如Line2D、 Rectangle、 Text、AxesImage 等等。而容器類型則可以包含許多簡單類型的Artists,

使它們組織成一個整體,例如Axis、 Axes、Figure等。

直接使用Artists創建圖表的標準流程如下:

創建Figure對象
    用Figure對象創建一個或者多個Axes或者Subplot對象
    調用Axies等對象的方法創建各種簡單類型的Artists

4.1、Artist 對象
    Artist對象共分爲簡單類型和容器類型兩種哦。
    下面是一個簡單Artist對象的創建過程:

複製代碼
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(1) # 創建了一個figure對象;

figure對象的add_axes()可以在其中創建一個axes對象,

add_axes()的參數爲一個形如[left, bottom, width, height]的列表,取值範圍在0與1之間;

我們把它放在了figure圖形的上半部分,對應參數分別爲:left, bottom, width, height;

ax = fig.add_axes([0.1, 0.5, 0.8, 0.5])
ax.set_xlabel(‘x’) # 用axes對象的set_xlabel函數來設置它的xlabel
ax.set_ylabel(‘y’)
line =ax.plot(range(5))[0] # 用axes對象的plot()進行繪圖,它返回一個Line2D的對象;
line.set_color(‘g’) # 再調用Line2D的對象的set_color函數設置color的屬性;
plt.show()
複製代碼
    輸出圖形:

5、figure 容器
    在構成圖表的各種Artist對象中,最上層的Artist對象是Figure。我們可以調用add_subplot()與add_axes()方法向圖表中添加子圖,它們分加到figure的axes的屬性列表中。

add_subplot()與add_axes()返回新創建的axes對象,分別爲axesSuubplot與axes, axesSuubplot爲 axes的派生類。另外,可以通過delaxes()方法來刪除哦;

figure對象可以有自己的簡單的artist對象。

下面列出Figure對象中包含的其他Artist對象的屬性:

axes:Axes對象列表;
    patch:作爲背景的Rectangle對象;
    images:FigureImage對象列表,用於顯示圖像;
    legends:Legend 對象列表,用於顯示圖示;
    lines:Line2D對象列表;
    patches:Patch對象列表;
    texts:Text 對象列表,用於顯示文字;

6、axes 容器
    它是整個matplotlib的核心,它包含了組成圖表的衆多的artist對象。並且有很多方法。我們常用的Line2D啦,Xaxis,YAxis等都是它的屬性哦;可以通過這個對象的屬性來設置座標軸的label,

範圍啦等之類的。乾脆直接用plt.getp()查看它的屬性,然後通過set_屬性名()函數來設置就好啦。

7、axis 容器
    axis容器包括了座標軸上的刻度線、刻度標籤等、座標網絡等內容。

座標軸上的每個刻度包括刻度線(ticklines)、刻度標籤(ticklabels)、刻度位置(ticklocs)。

例子:

複製代碼
import numpy as np
import matplotlib.pyplot as plt

通過axis來更改座標軸

plt.plot([1,2,3],[4,5,6])

gca()獲取當前的axes繪圖區域,調用gcf()來獲得當前的figure

axis = plt.gca().xaxis
axis.get_ticklocs() # 得到刻度位置;
axis.get_ticklabels() # 得到刻度標籤;
axis.get_ticklines() # 得到刻度線;
axis.get_ticklines(minor = True) # 得到次刻度線; 舉個例子:就像我們的尺子上的釐米的爲主刻度線,毫米的爲次刻度線;
for label in axis.get_ticklabels():
label.set_color(‘blue’) # 設置每個刻度標籤的顏色;
label.set_rotation(90) # 旋轉45度;
label.set_fontsize(16) # 設置字體大小;
for line in axis.get_ticklines():
line.set_color(‘green’)
line.set_markersize(3) # 設置刻度線的長短;
line.set_markeredgewidth(2) # 設置線的粗細
plt.show()
複製代碼
    運行結果:

pyplot函數提供了兩個繪製文字的函數:text()和figtext()。它們分別調用了當前的Axes對象與當前的Figure對象的text()方法進行繪製文字。

text()默認在數字座標系(就是axes在的座標系,用座標軸的數字來表示座標)中畫, figtext()默認在圖表座標系(就是figure在圖表中,座標範圍從0 到 1 )中畫,

簡單的調用:

plt.text(1, 1, ‘hello,world’, color = ‘bule’) #還可以寫更多參數的;
    plt.figtexe(0.1, 0.8 ,”i am in figure’, color = ‘green’)

8、常用函數
    plot()

可以畫出很簡單線圖,基本用法:

lot(x, y) # 畫出橫軸爲x與縱軸爲y的圖,使用默認的線形與顏色;

plot(x, y, ‘bo’) # 用藍色,且點的標記用小圓,下面會解釋哦

plot(y) # 縱軸用y ,橫軸用y的每個元素的座標,即0,1,2……

plot(y, ‘r+’) # 如果其中x或y 爲2D的,則會用它的相應的每列來表示(注意是每列)

plot(x1, y1, ‘g^’, x2, y2, ‘g-’) #可以使用多對的x, y, format 對當作變量的,把它們畫一個圖裏;

對於參數中,常用的format:線的顏色、線的形狀、點的標記形狀,我們用這三個的時候經常用縮寫,它們之間的順序怎麼都可以,

如它倆一個意思:’r+–’、’+–r’。如果我們不想縮寫的話,可以分別寫成如: color=’green’, linestyle=’dashed’, marker=’o’。

線的形狀:
    ‘-’ solid line style
    ‘–’ dashed line style
    ‘-.’ dash-dot line style
    ‘:’ dotted line style

點的標記:

‘.’ point marker

‘,’ pixel marker

‘o’ circle marker

‘v’ triangle_down marker

‘^’ triangle_up marker

‘<’ triangle_left marker

‘>’ triangle_right marker

‘1’ tri_down marker

‘2’ tri_up marker

‘3’ tri_left marker

‘4’ tri_right marker

‘s’ square marker

‘p’ pentagon marker

‘*’ star marker

‘h’ hexagon1 marker

‘H’ hexagon2 marker

‘+’ plus marker

‘x’ x marker

‘D’ diamond marker

‘d’ thin_diamond marker

‘|’ vline marker

‘_’ hline marker

線的顏色:

‘b’ blue
    ‘g’ green
    ‘r’ red
    ‘c’ cyan
    ‘m’ magenta
    ‘y’ yellow
    ‘k’ black
    ‘w’ white

常見線的屬性有:color,labor,linewidth,linestyle,maker,等,參考:lines–matplotlib。

顯示正弦曲線

複製代碼
import numpy as np
import matplotlib.pyplot as plt

plt.figure(‘正弦曲線’) # 調用figure函數創建figure(1)對象,可以省略,這樣那plot時,它就自動建一個啦;

t = np.arange(0.0, 4.0, 0.1)
s = np.sin(np.pi*t)
plt.plot(t, s, ‘g–o’, label = ‘sinx’)

plt.legend() # 顯示右上角的那個label,即上面的label = ‘sinx’
plt.xlabel(‘time (s)’) # 設置x軸的label,pyplot模塊提供了很直接的方法,內部也是調用的上面當然講述的面向對象的方式來設置;
plt.ylabel(‘voltage (mV)’) # 設置y軸的label;
#plt.xlim(-1,3) # 可以自己設置x軸的座標的範圍哦;
#plt.ylim(-1.5,1.5)
plt.title(‘About as simple as it gets, folks’)
plt.grid(True) # 顯示網格;

plt.show()
複製代碼
  輸出圖形:

subplot()
    利用subplot()函數可以返回一個axes的對象,函數爲:subplot(numRows, numCols, plotnum),當這三個參數都小於10時,可以把它們寫一起,如下所示:

複製代碼

填充彩色子圖

import matplotlib.pyplot as plt
import numpy as np

for i, color in enumerate(‘rgbyck’):
plt.subplot(321+i, facecolor = color)
plt.show()
複製代碼
    輸出圖形:

利用subplot_adjust()函數可以對畫的多個子圖進行調整,優化間隔,它一共有left、right, bottom, top, wspace, hspase 六個參數,取 值從0至1。

複製代碼

填充彩色子圖

import matplotlib.pyplot as plt
import numpy as np
x1 = np.linspace(0.0, 5.0) #生成一個一維的array,linspace(起始點,結束點,點數(默認爲50))
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 2, 1) #表示在subplot爲2*1的樣式,並在第一個子圖上畫出;
plt.plot(x1, y1, ‘yo-’)
plt.title(‘A tale of 2 subplots’)
plt.ylabel(‘Damped oscillation’)

plt.subplot(2, 2, 2) # 我們在第二個子圖上加個空圖哈,去理解它的圖的排序(即注意第二個子圖的位置
# 爲第一行第二列)是按行優先的,這個正好和matlab裏相反哦;
plt.title(‘It is a empty figure’)

plt.subplot(2, 2, 4)
plt.plot(x2, y2, ‘g.-’)
plt.xlabel(‘time (s)’)
plt.ylabel(‘Undamped’)

plt.show()
複製代碼
    輸出圖形:

subplots()
    plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, **fig_kw)

作用:創建一個已有subplots的figures;
    參數:

nrows : int ,指創建的sublots的行數,默認爲1.

ncols : int ,指創建的sublots的列數,默認爲1.

sharex : 爲一個string或bool類型; 當爲Ture時,所有的subpots將要共享x軸,如果它們是上下的關係的話,上面的圖的刻度label就沒有,只有下面那個圖的.

複製代碼
If a string must be one of “row”, “col”, “all”, or “none”.
“all” has the same effect as True, “none” has the same effect
as False.
If “row”, each subplot row will share a X axis.
If “col”, each subplot column will share a X axis and the x tick
labels on all but the last row will have visible set to False.

sharey : 同上

squeeze : bool 它是用來控制返回值的,根據返回的axis的結果決定要不要把沒有的維度進行壓縮一下.
當爲Ture時,如果返回的axis只有一個,則表示成標量,如果有一行或一列,則表示爲一維數組,如果多行多列,則表示爲2D數組;
當爲False時,不管多少個返回的axis,都以二維數組的方式返回;
subplot_kw : dict
Dict with keywords passed to the
:meth:~matplotlib.figure.Figure.add_subplot call used to
create each subplots.

fig_kw : dict
Dict with keywords passed to the :func:figure call. Note that all
keywords not recognized above will be automatically included here.
複製代碼

返回值

有兩個fig和 axt(它是元組的方式)

fig is the :class:matplotlib.figure.Figure object

*ax * can be either a single axis object or an array of axis objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above.

複製代碼

subplots() 返回值

import matplotlib.pyplot as plt
import numpy as np

x = range(0,30,1)
y = np.sin(x)

接收返回的兩個對象

f,(ax1, ax2) = plt.subplots(1, 2, sharey=True)

兩個對象分別畫圖

ax1.plot(x, y)
ax1.set_title(‘Sharing Y axis’)
ax2.scatter(x, y)
plt.show()
複製代碼
   輸出圖形:

twinx()或twiny()
    twinx():在同一圖畫中,共享x軸,但是擁有各自不同的y軸

twiny():和上面一樣,不同之處在於,它共享y軸。

複製代碼

twinx() 共享x軸實例

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(1)
ax1 =plt.subplot(111)

ax2 = ax1.twinx()

ax1.plot(np.arange(1,5),‘g–’)
ax1.set_ylabel(‘ax1’,color = ‘r’)
ax2.plot(np.arange(7,10),‘b-’)
ax2.set_ylabel(‘ax2’,color = ‘b’)

plt.show()
複製代碼
    輸出圖形:

參考文章:
  matplotlib.pyplot 官方文檔
  博客園——matplotlib 常用知識
  博客園——matplotlib 繪圖入門
  matplotlib-繪製精美的圖表(Figure容器,Artist對象,Axes容器)
  博客園——Matplotlib 詳解圖像各個部分
  
  Matplotlib.pyplot 常用方法(一)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章