matplotlib繪圖的基本操作


更簡明易懂看Matplotlib Python 畫圖教程 (莫煩Python)_演講•公開課_科技_bilibili_嗶哩嗶哩 https://www.bilibili.com/video/av16378354/#page=1

 

plt.plot(x,y , fmt)  :繪制坐標圖

plt.boxplot(data, notch, position): 繪制箱形圖

plt.bar(left, height, width, bottom) : 繪制條形圖

plt.barh(width, bottom, left, height) : 繪制橫向條形圖

plt.polar(theta, r) : 繪制極坐標圖

plt.pie(data, explode) : 繪制餅圖

plt.scatter(x, y) :繪制散點圖

plt.hist(x, bings, normed) : 繪制直方圖

 

繪制圖表的一些基本操作:

tips:如果你向plot()指令提供了一維的數組或列表,那么matplotlib將默認它是一系列的y值,並自動為你生成x的值,默認的x向量從0開始並且具有和y同樣的長度。

 

"""matplotlib繪圖的基本操作"""


import matplotlib.pyplot as plt
import numpy as np

# 繪制普通圖像
x = np.linspace(-2*np.pi, 2*np.pi, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.cos(2*x)

# 創建figure對象,生成畫板  # 參數依次是圖名,大小,dpi,背景色,邊緣色
plt.figure(num='正余弦函數圖', figsize=(10, 6), dpi=120, facecolor='y', edgecolor='g')
    # 在繪制時設置lable, 逗號是必須的
l1 = plt.plot(x, y1, color='red', linestyle='-', linewidth=0.5, label='$sin(x)$')
l2 = plt.plot(x, y2, 'b', label='$cos(x)$')
    # plt.plot(x, y1, 'r--', x, y2, 'b-.', x, y3, 'g') 疊加圖 在一個圖畫出多條不同格式的線
    # 設置坐標軸的取值范圍
plt.axis((-6.5, 6.5, -1.1, 1.1))
    # plt.xlim((-6.5, 6.5))
    # plt.ylim((-1.1, 1.1))


# 設置坐標軸的lable
plt.xlabel('X axis')
plt.ylabel('Y axis')
# 設置x坐標軸刻度, 原來為0.25, 修改后為0.5 # plt.xticks(np.linspace(-2*np.pi, 2*np.pi, 9))
# 第一個參數是位置,第二個參數是標簽lable,$使字體傾斜,\ 輸出空格,\alpha_i輸出數學符號α1也可直接alpha
plt.xticks((-2*np.pi, -3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi),
           ('$-2π$', '$-3π/2$', '$-π$', '$-π/2$', r'$0\ \alpha_i$', 'π/2', 'π', '3π/2', ''))
plt.yticks((-1, 0, 1))

# 設置、顯示legend
plt.legend(loc='best')  # loc參數設置圖例顯示的位置


# 設置圖表的標題
plt.title('cos&sin')
plt.text(-np.pi, 1, '任意位置添加文字',fontdict={'size': 10, 'color': 'y'})  # text在圖中任意位置添加文字,前兩個參數是左下角的位置坐標
plt.annotate('max', xy=(0, 1), xytext=(1, 1.05), arrowprops=dict(facecolor='k', shrink=1))  # 注釋的地方xy(x,y)和插入文本的地方xytext(x1,y1)


# 移動坐標軸,spines為脊梁,即4個邊框
ax = plt.gca()  # gca stands for 'get current axis'
ax.spines['right'].set_color('none')  # 設置右‘脊梁’為無色
ax.spines['top'].set_color('none')  # 設置上‘脊梁’為無色
ax.xaxis.set_ticks_position('bottom')  # 底部‘脊梁’設置為X軸
ax.spines['bottom'].set_position(('data', 0))  # 底部‘脊梁’移動位置,y的data
ax.yaxis.set_ticks_position('left')  # 左部‘脊梁’設置為Y軸
ax.spines['left'].set_position(('data', 0))  # 左部‘脊梁’移動位置,x的data


# 給特殊點做注釋,在2π/3的位置給兩條函數曲線加一個注釋
plt.plot([2*np.pi/3, 2*np.pi/3], [0, np.sin(2*np.pi/3)], 'r--')  # xy是基於xycoords的data
plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', xy=(2*np.pi/3, np.sin(2*np.pi/3)), xycoords='data',
             xytext=(+10, +30), textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle="->",
             connectionstyle="arc3,rad=.2"))  # +10,+30表示基於xy加10,加30,textcoords='offset points'代表基於xy
plt.scatter([2*np.pi/3], [np.sin(2*np.pi/3)], 40, 'r')  # 繪制點x,y,大小,顏色
plt.plot([2*np.pi/3, 2*np.pi/3], [0, np.cos(2*np.pi/3)], 'b--')
plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(2*np.pi/3, np.cos(2*np.pi/3)), xycoords='data',
             xytext=(-90, -50), textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle="->",
             connectionstyle="arc3,rad=.2"))  # arrowprops設置指示線的格式,connectionstyle設置線的角度,弧度
plt.scatter([2*np.pi/3], [np.cos(2*np.pi/3)], 40, 'b')
plt.show()

 

 

 

 

 以下參考自 Python--matplotlib繪圖可視化知識點整理 - michael翔的IT私房菜 - SegmentFault https://segmentfault.com/a/1190000005104723

線條風格linestyle 描述    
'-' 實線 ':' 虛線
'--' 破折線 'None',  ' ',  '' 什么都不畫
'-.' 點划線

 

線條標記maker 描述    
'o' 圓圈 '.'
'D' 菱形 's' 正方形
'h' 六邊形1 '*' 星號
'H' 六邊形2 'd' 小菱形
'_' 水平線 'v' 一角朝下的三角形
'8' 八邊形 '<' 一角朝左的三角形
'p' 五邊形 '>' 一角朝右的三角形
',' 像素 '^' 一角朝上的三角形
'+' 加號 '\’ 豎線  
'None','',' ' 'x' X

 

顏色

可以通過調用matplotlib.pyplot.colors()得到matplotlib支持的所有顏色。

別名 顏色 別名 顏色
b 藍色 g 綠色
r 紅色 y 黃色
c 青色 k 黑色
m 洋紅色 w 白色

如果這兩種顏色不夠用,還可以通過兩種其他方式來定義顏色值:

  • 使用HTML十六進制字符串 color='eeefff' 使用合法的HTML顏色名字('red','chartreuse'等)。

  • 也可以傳入一個歸一化到[0,1]的RGB元祖。 color=(0.3,0.3,0.4)

很多方法可以介紹顏色參數,如title()。

plt.tilte('Title in a custom color',color='#123456')

 

背景色

通過向如matplotlib.pyplot.axes()或者matplotlib.pyplot.subplot()這樣的方法提供一個axisbg參數,可以指定坐標這的背景色。

subplot(111,axisbg=(0.1843,0.3098,0.3098)  

 

標題title matplotlib命令與格式:標題(title),標注(annotate),文字說明(text) - CSDN博客 http://blog.csdn.net/helunqu2017/article/details/78659490

 

(1)title常用參數
fontsize設置字體大小,默認12,可選參數 ['xx-small', 'x-small', 'small', 'medium', 'large','x-large', 'xx-large']
fontweight設置字體粗細,可選參數 ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
fontstyle設置字體類型,可選參數[ 'normal' | 'italic' | 'oblique' ],italic斜體,oblique傾斜
verticalalignment設置水平對齊方式 ,可選參數 : 'center' , 'top' , 'bottom' ,'baseline' 
horizontalalignment設置垂直對齊方式,可選參數:left,right,center
rotation(旋轉角度)可選參數為:vertical,horizontal 也可以為數字
alpha透明度,參數值0至1之間
backgroundcolor標題背景顏色
bbox給標題增加外框 ,常用參數如下:
  • boxstyle方框外形
  • facecolor(簡寫fc)背景顏色
  • edgecolor(簡寫ec)邊框線條顏色
  • edgewidth邊框線條大小

(2)title例子

plt.title('Interesting Graph',fontsize='large',fontweight='bold') 設置字體大小與格式
plt.title('Interesting Graph',color='blue') 設置字體顏色
plt.title('Interesting Graph',loc ='left') 設置字體位置
plt.title('Interesting Graph',verticalalignment='bottom') 設置垂直對齊方式
plt.title('Interesting Graph',rotation=45) 設置字體旋轉角度
plt.title('Interesting',bbox=dict(facecolor='g', edgecolor='blue', alpha=0.65 )) 標題邊框

面向對象api例子:

            import matplotlib.pyplot as plt  

            x=[1,2,3,4,5]  

            y=[3,6,7,9,2]  

            fig,ax=plt.subplots(1,1)  

            ax.plot(x,y,label='trend')  

            ax.set_title('title test',fontsize=12,color='r')  

            plt.show()</span>  

 

plt.annotate()文本注釋

在數據可視化的過程中,圖片中的文字經常被用來注釋圖中的一些特征。使用annotate()方法可以很方便地添加此類注釋。在使用annotate時,要考慮兩個點的坐標:被注釋的地方xy(x, y)和插入文本的地方xytext(x, y), 見以上程序。

 

(1)annotate語法說明 :annotate(s='str' ,xy=(x,y) ,xytext=(l1,l2) ,..)

s 為注釋文本內容 
xy 為被注釋的坐標點
xytext 為注釋文字的坐標位置
xycoords 參數如下:

  • figure points          points from the lower left of the figure 點在圖左下方
  • figure pixels          pixels from the lower left of the figure 圖左下角的像素
  • figure fraction       fraction of figure from lower left 左下角數字部分
  • axes points           points from lower left corner of axes 從左下角點的坐標
  • axes pixels           pixels from lower left corner of axes 從左下角的像素坐標
  • axes fraction        fraction of axes from lower left 左下角部分
  • data                     use the coordinate system of the object being annotated(default) 使用的坐標系統被注釋的對象(默認)
  • polar(theta,r)       if not native ‘data’ coordinates t

extcoords 設置注釋文字偏移量

         | 參數 | 坐標系 | 
         | 'figure points' | 距離圖形左下角的點數量 | 
         | 'figure pixels' | 距離圖形左下角的像素數量 | 
         | 'figure fraction' | 0,0 是圖形左下角,1,1 是右上角 | 
         | 'axes points' | 距離軸域左下角的點數量 | 
         | 'axes pixels' | 距離軸域左下角的像素數量 | 
         | 'axes fraction' | 0,0 是軸域左下角,1,1 是右上角 | 
         | 'data' | 使用軸域數據坐標系 |

arrowprops  #箭頭參數,參數類型為字典dict

  • width           the width of the arrow in points                              點箭頭的寬度
  • headwidth   the width of the base of the arrow head in points  在點的箭頭底座的寬度
  • headlength  the length of the arrow head in points                   點箭頭的長度
  • shrink          fraction of total length to ‘shrink’ from both ends  總長度為分數“縮水”從兩端
  • facecolor     箭頭顏色

bbox給標題增加外框 ,常用參數如下:

  •   boxstyle方框外形
  •   facecolor(簡寫fc)背景顏色
  •   edgecolor(簡寫ec)邊框線條顏色
  •   edgewidth邊框線條大小

 bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k',lw=1 ,alpha=0.5)  #fc為facecolor,ec為edgecolor,lw為lineweight

(2)案例

  1. import matplotlib.pyplot as plt  
  2. import numpy as np  
  3. x = np.arange(0, 6)  
  4. y = x * x  
  5. plt.plot(x, y, marker='o')  
  6. for xy in zip(x, y):  
  7.     plt.annotate("(%s,%s)" % xy, xy=xy, xytext=(-20, 10), textcoords='offset points')  
  8. plt.show()  

 
  1. <span style="font-size:14px;">plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='black', shrink=0.05))</span>  

 

移動坐標系(Spines)

Spines 是連接軸刻度標記的線,是軸的邊界,而且標明了數據區域的邊界,可以被放置在任意位置。我們想要spines 置於中間。因為有四個spine(上下左右),我們將要通過設置顏色(無)丟棄上面和右側的部分, 進而移動下面和左邊的線到坐標0(數據空間)。 代碼見上

 

text設置文字說明

 

(1)text語法說明

text(x,y,string,fontsize=15,verticalalignment="top",horizontalalignment="right")

 

x,y:表示坐標值上的值
string:表示說明文字
fontsize:表示字體大小
verticalalignment:垂直對齊方式 ,參數:[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
horizontalalignment:水平對齊方式 ,參數:[ ‘center’ | ‘right’ | ‘left’ ]
xycoords選擇指定的坐標軸系統:

  • figure points          points from the lower left of the figure 點在圖左下方
  • figure pixels          pixels from the lower left of the figure 圖左下角的像素
  • figure fraction       fraction of figure from lower left 左下角數字部分
  • axes points           points from lower left corner of axes 從左下角點的坐標
  • axes pixels           pixels from lower left corner of axes 從左下角的像素坐標
  • axes fraction        fraction of axes from lower left 左下角部分
  • data                     use the coordinate system of the object being annotated(default) 使用的坐標系統被注釋的對象(默認)
  • polar(theta,r)       if not native ‘data’ coordinates t

 

arrowprops  #箭頭參數,參數類型為字典dict

  • width           the width of the arrow in points                              點箭頭的寬度
  • headwidth   the width of the base of the arrow head in points  在點的箭頭底座的寬度
  • headlength  the length of the arrow head in points                   點箭頭的長度
  • shrink          fraction of total length to ‘shrink’ from both ends  總長度為分數“縮水”從兩端
  • facecolor     箭頭顏色

 

bbox給標題增加外框 ,常用參數如下:

  •   boxstyle方框外形
  •   facecolor(簡寫fc)背景顏色
  •   edgecolor(簡寫ec)邊框線條顏色
  •   edgewidth邊框線條大小

 bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k',lw=1 ,alpha=0.5)  #fc為facecolor,ec為edgecolor,lw為lineweight

(2)案例

文字格式與位置:
  1. import matplotlib.pyplot as plt  
  2. fig = plt.figure()  
  3. plt.axis([0, 10, 0, 10])  
  4. t = "This is a really long string that I'd rather have wrapped so that it"\  
  5.     " doesn't go outside of the figure, but if it's long enough it will go"\  
  6.     " off the top or bottom!"  
  7. plt.text(4, 1, t, ha='left', rotation=15, wrap=True)  
  8. plt.text(6, 5, t, ha='left', rotation=15, wrap=True)  
  9. plt.text(5, 5, t, ha='right', rotation=-15, wrap=True)  
  10. plt.text(5, 10, t, fontsize=18, style='oblique', ha='center',va='top',wrap=True)  
  11. plt.text(3, 4, t, family='serif', style='italic', ha='right', wrap=True)  
  12. plt.text(-1, 0, t, ha='left', rotation=-15, wrap=True)  
  13. plt.show()  

花式文本框:
  1. import matplotlib.pyplot as plt  
  2. plt.text(0.6, 0.5, "test", size=50, rotation=30.,ha="center", va="center",bbox=dict(boxstyle="round",ec=(1., 0.5, 0.5),fc=(1., 0.8, 0.8),))  
  3. plt.text(0.5, 0.4, "test", size=50, rotation=-30.,ha="right", va="top",bbox=dict(boxstyle="square",ec=(1., 0.5, 0.5),fc=(1., 0.8, 0.8),))  
  4. plt.draw()  
  5. plt.show()  


數學公式:

  1. plt.title(r'$\alpha_i > \beta_i$', fontsize=20)  
  2. plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)  
  3. plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',fontsize=20)  

 


免責聲明!

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



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