Python常用包學習(三)matplotlib包(理論+動手實踐)

Python常用包學習(三)matplotlib包(理論+動手實踐)

Python最常用的繪圖庫,提供了一整套十分適合交互式繪圖的命令API,比較方便的就可以將其嵌入到GUI應用程序中。

官網:http://matplotlib.org/

 

FigureSubplot

  • Figure:面板(圖),matplotlib中的所有圖像都是位於figure對象中,一個圖像只能有一個figure對象。
  •  Subplot:子圖,figure對象下創建一個或多個subplot對象(即axes)用於繪製圖像。

 

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
#解決中文顯示問題
mpl.rcParams['font.sans-serif']=[u'SimHei']
mpl.rcParams['axes.unicode_minus']=False
#獲取figure對象
fig=plt.figure(figsize=(8,6))
#在figure上創建axes對象
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
#在當前axes上繪製曲線(ax3)
# print(np.random.randn(50).cumsum())
plt.plot(np.random.randn(50).cumsum(),'k--')
#在ax1上繪製曲線
ax1.hist(np.random.rand(300),bins=20,color='k',alpha=0.3)
#在ax2上繪製曲線
ax2.scatter(np.arange(30),np.arange(30)+3*np.random.randn(30))

#展示
plt.show()

 

#解決中文顯示問題和負號現實問題
mpl.rcParams['font.sans-serif']=['FangSong']
mpl.rcParams['axes.unicode_minus']=False

fig,axes=plt.subplots(2,2,sharex=True,sharey=True)  #共享x/y軸
#print(axes)
for i in range(2):
    for j in range(2):
        axes[i,j].hist(np.random.randn(500),bins=10,color='b',alpha=0.5)

plt.subplots_adjust(wspace=0,hspace=0)
plt.show()

 

matplotlib曲線圖

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
#解決中文顯示問題和負號現實問題
mpl.rcParams['font.sans-serif']=['FangSong']
mpl.rcParams['axes.unicode_minus']=False

x=np.linspace(0,10,1000)
y=np.sin(x)
z=np.cos(x**2)
plt.figure(figsize=(8,6))   #創建一個繪圖對象,並且指定寬8英寸,高6英寸
#plt.plot(x,y,label='$sin(x)$',color='blue',linewidth=2)
#label:給所繪製的曲線一個名字,此名字在圖示的(legend)中顯示
plt.plot(x,y,label='$sin(x)$',linewidth=10)
plt.plot(x,z,"b--",label='$cos(x^2)$')
plt.xlabel('Time(s)')  #設置x軸標籤
plt.ylabel('volt')   #設置y軸標籤
plt.title("TEST")    #設置圖標標題
plt.ylim(-1.2,1.2)   #設置y軸範圍
plt.legend()     #顯示圖示說明
plt.grid(True)    #顯示虛線框
plt.show()    #展示圖表

 

matplotlib繪製散點圖

import matplotlib.pyplot as plt
import matplotlib as mpl
#解決中文顯示問題和負號現實問題
mpl.rcParams['font.sans-serif']=['FangSong']
mpl.rcParams['axes.unicode_minus']=False
#plt.figure(figsize=(16,10))
plt.axis([0,5,0,20])
plt.title("Pictuer",fontsize=20,fontname="Times New Roman")
plt.xlabel('Counting',color="gray")
plt.ylabel('square',color="gray")
plt.text(1,1.5,"第一")
plt.text(2,4.5,"第二")
plt.text(3,9.5,"第三")
plt.text(4,16.5,"第四")
plt.text(1,11.5,r"$y=x^2$",fontsize=20,bbox={'facecolor':'yellow','alpha':0.2})
plt.grid(True)
plt.plot([1,2,3,4],[1,4,9,16],"ro")
plt.plot([1,2,3,4],[0.8,3.5,8,15],"g^")
plt.plot([1,2,3,4],[0.5,2.5,5.4,12],"b*")
plt.legend(['first series','second series','third sreies'],loc=2)
plt.savefig(r"C:\學習資料\python基礎\第19節課-numpy與pandas\我的圖片.png")
plt.show()

 

顏色、標記和線型

  **Colors**
    
    The following color abbreviations are supported:
    
    =============    ===============================
    character        color
    =============    ===============================
    ``'b'``          blue
    ``'g'``          green
    ``'r'``          red
    ``'c'``          cyan
    ``'m'``          magenta
    ``'y'``          yellow
    ``'k'``          black
    ``'w'``          white
    =============    ===============================
    
    If the color is the only part of the format string, you can
    additionally use any  `matplotlib.colors` spec, e.g. full names
    (``'green'``) or hex strings (``'#008000'``).
    
    **Markers**
    
    =============    ===============================
    character        description
    =============    ===============================
    ``'.'``          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
    =============    ===============================
    
    **Line Styles**
    
    =============    ===============================
    character        description
    =============    ===============================
    ``'-'``          solid line style
    ``'--'``         dashed line style
    ``'-.'``         dash-dot line style
    ``':'``          dotted line style
    =============    ===============================
    
    Example format strings::
    
        'b'    # blue markers with default shape
        'ro'   # red circles
        'g-'   # green solid line
        '--'   # dashed line with default color
        'k^:'  # black triangle_up markers connected by a dotted line
    
import matplotlib.pyplot as plt
import numpy as np
from pylab import mpl
#解決中文顯示問題和負號現實問題
mpl.rcParams['font.sans-serif']=['FangSong']
mpl.rcParams['axes.unicode_minus']=False
x=np.arange(-5,5,0.2)
y=np.sin(x)
plt.axis([-5,5,-1,1])
#plt.plot(x,y,color="g",linestyle="dashed",marker="o")
#也可以簡寫成
plt.plot(x,y,"go--")
plt.text(-2,0.75,"$y=sin(x)$",fontsize=15,bbox={'facecolor':'yellow','alpha':0.3})
plt.show()

 

刻度、標籤和圖例

 

圖像保存文件

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