Matplotlib 是一個python 的繪圖庫,主要用于生成2D圖表。
常用到的是matplotlib中的pyplot,導入方式import matplotlib.pyplot as plt
一、顯示圖表的模式
1.plt.show()
該方式每次都需要手動show()才能顯示圖表,由于pycharm不支持魔法函數,因此在pycharm中都需要采取這種show()的方式。
arr = np.random.rand(10) plt.plot(arr) plt.show() #每次都需要手動show()
?
2.魔法函數%matplotlib inline
魔法函數不需要手動show(),可直接生成圖表,但是魔法函數無法在pycharm中使用,下面都是在jupyter notebook中演示。
inline方式直接在代碼的下方生成一個圖表。
%matplotlib inline x = np.random.rand(1000) y = np.random.rand(1000) plt.scatter(x,y) #最基本散點圖 # <matplotlib.collections.PathCollection at 0x54b2048>
?
?3.魔法函數%matplotlib notebook
%matplotlib notebook s = pd.Series(np.random.rand(100)) s.plot(style = 'k--o',figsize = (10,5))
notebook方式,代碼需要運行兩次,會在代碼下方生成一個可交互的圖表,可對圖表進行放大、拖動、返回原樣等操作。?
?
4.魔法函數%matplotlib qt5
%matplotlib qt5 plt.gcf().clear() df = pd.DataFrame(np.random.rand(50,2),columns=['A','B']) df.hist(figsize=(12,5),color='g',alpha=0.8)
qt5方式會彈出一個獨立于界面上的可交互圖表。
由于可交互的圖表比較占內存,運行起來稍顯卡,因此常采用inline方式。
二、生成圖表的方式
1.Seris生成
ts = pd.Series(np.random.randn(50),index=pd.date_range('2019/1/1/',periods=50)) ts = ts.cumsum() ts.plot()
?
2.DataFrame生成
df = pd.DataFrame(np.random.rand(20,3),columns=['A','B','C']) df.plot()
?
三、圖表的基本元素
plot的使用方法,以下圖表都在%matplotlib inline 模式下生成。


plot(kind='line',ax=None,figsize=None,use_index=True,title=None,grid=None,legend=None,\style=None,logx=False,logy=False,loglog=False,xticks=None,yticks=None,xlim=None,\ylim=None,rot=None,fontsize=None,colormpap=None,subplots=False,table=False,xerr=None,yerr=None,\lable=None,secondary_y=False,**kwargs) # kind:圖表類型,默認為line折線圖,其他bar直方圖、barh橫向直方圖 # ax:第幾個子圖 # figsize:圖表大小,即長和寬,默認為None,指定形式為(m,n) # use_index:是否以原數據的索引作為x軸的刻度標簽,默認為True,如果設置為False則x軸刻度標簽為從0開始的整數 # title:圖表標題,默認為None # grid:是否顯示網格,默認為None,也可以直接使用plt.grid() # legend:如果圖表包含多個序列,序列的注釋的位置 # style:風格字符串,包含了linestyle、color、marker,默認為None,如果單獨指定了color以color的顏色為準 # color:顏色,默認為None # xlim和ylim:x軸和y軸邊界 # xticks和yticks:x軸和y軸刻度標簽 # rot:x軸刻度標簽的逆時針旋轉角度,默認為None,例如rot = 45表示x軸刻度標簽逆時針旋轉45° # fontsize:x軸和y軸刻度標簽的字體大小 # colormap:如果一個圖表上顯示多列的數據,選擇顏色族以區分不同的列 # subplots:是否分子圖顯示,默認為None,如果一個圖標上顯示多列的數據,是否將不同的列拆分到不同的子圖上顯示 # label:圖例標簽,默認為None,DataFrame格式以列名為label # alpha:透明度
?
圖表名稱,x軸和y軸的名稱、邊界、刻度、標簽等屬性。
import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame(np.random.rand(10,2),columns=['A','B']) fig = df.plot(figsize=(6,4)) #figsize表示圖表大小,即長和寬 plt.title('test') #圖表名稱 plt.xlabel('x-axis') #x軸名稱 plt.ylabel('y-axis') #y軸名稱 plt.legend(loc=0) #圖表位置 plt.xlim([0,10]) #x軸邊界 plt.ylim([0,1]) #y軸邊界 plt.xticks(range(1,10)) #x軸刻度間隔 plt.yticks([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]) #y軸刻度間隔 fig.set_xticklabels('%d'%i for i in range(1,10)) #x軸顯示標簽,設置顯示整數 fig.set_yticklabels('%.2f'%i for i in [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]) #y軸顯示標簽,設置顯示2位小數# legend的loc,位置 # 0:best # 1:upper right # 2:upper left # 3:lower left # 4:lower right # 5:right # 6:center left # 7:center right # 8:lower center # 9:upper center # 10:center
?
是否顯示網格及網格屬性、是否顯示坐標軸、刻度方向等。
x = np.linspace(-np.pi,np.pi,500) c,s = np.cos(x),np.sin(x) plt.plot(x,c) plt.plot(x,s) plt.grid(linestyle = '--',color = 'gray',linewidth = '0.5',axis = 'both') #plt.grid()表示顯示網格,參數分別表示網格線型、顏色、寬度、顯示軸(x,y,both表示顯示x軸和y軸) plt.tick_params(bottom='on',top='off',left='on',right='off') #是否顯示刻度,默認left和bottom顯示import matplotlib matplotlib.rcParams['xtick.direction']='in' matplotlib.rcParams['ytick.direction']='in' #刻度的顯示方向,默認為out,in表示向內,out表示向外,inout表示穿透坐標軸內外都有 frame = plt.gca() # plt.axis('off') #關閉坐標軸 # frame.axes.get_xaxis().set_visible(False) #x軸不可見 # frame.axes.get_yaxis().set_visible(False) #y軸不可見


linestyle:線型-:實線,默認--:虛線-.:一個實線一個點::點
?


marker:值在x刻度上的顯示方式'.' 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
?


color:顏色r:red紅色y:yello黃色 g:green綠色b:blue藍色k:black黑色 alpha:透明度,0-1之間colormap: Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r
?
?
也可在創建圖表時通過style='線型顏色顯示方式'
例如style = '-ro'表示設置線條為實現、顏色為紅色,marker為實心圓
?
使用python內置的風格樣式style,需導入另外一個模塊import matplotlib.style as psl
import matplotlib.style as psl print(psl.available) psl.use('seaborn') plt.plot(pd.DataFrame(np.random.rand(20,2),columns=['one','two']))
?
?設置主刻度、此刻度、刻度標簽顯示格式等
from matplotlib.ticker import MultipleLocator,FormatStrFormatter t = np.arange(0,100) s = np.sin(0.1*np.pi*t)*np.exp(-0.01*t) ax = plt.subplot() #不直接在plot中設置刻度 plt.plot(t,s,'-go') plt.grid(linestyle='--',color='gray',axis='both')xmajorLocator = MultipleLocator(10) #將x主刻度標簽設置為10的倍數 xmajorFormatter = FormatStrFormatter('%d') #x主刻度的標簽顯示為整數 xminorLocator = MultipleLocator(5) #將x次刻度標簽設置為5的倍數 ax.xaxis.set_major_locator(xmajorLocator) #設置x軸主刻度 ax.xaxis.set_major_formatter(xmajorFormatter) #設置x軸主刻度標簽的顯示格式 ax.xaxis.set_minor_locator(xminorLocator) #設置x軸次刻度 ax.xaxis.grid(which='minor') #設置x軸網格使用次刻度 ymajorLocator = MultipleLocator(0.5) ymajorFormatter = FormatStrFormatter('%.2f') yminorLocator = MultipleLocator(0.25) ax.yaxis.set_major_locator(ymajorLocator) ax.yaxis.set_major_formatter(ymajorFormatter) ax.yaxis.set_minor_locator(yminorLocator) ax.yaxis.grid(which='minor')# ax.xaxis.set_major_locator(plt.NullLocator) #刪除x軸的主刻度 # ax.xaxis.set_major_formatter(plt.NullFormatter) #刪除x軸的標簽格式 # ax.yaxis.set_major_locator(plt.NullLocator) # ax.yaxis.set_major_formatter(plt.NullFormatter)
?
?
注釋和圖表保存
注釋:plt.text(x軸值,y軸值,'注釋內容')
水平線:plt.axhline(x值)
數值線:plt.axvline(y值)
刻度調整:plt.axis('equal')設置x軸和y軸每個單位表示的刻度相等
子圖位置調整:plt.subplots_adjust(left=None, bottom=None, right=None, top=None,wspace=None, hspace=None),子圖距離畫板上下左右的距離,子圖之間的寬度和高度
保存:plt.savefig(保存路徑及文件名稱,dpi=n,bbox_inches='tight',facecolor='red',edgecolor='yellow')
dpi表示分辨率,值越大圖片越清晰;bbox_inches為tight表示嘗試剪去圖表周圍空白部分,facecolor為圖表背景色,默認為白色,edgecolor為邊框顏色,默認為白色。
df = pd.DataFrame({'A':[1,3,2,6,5,8,5,9],'B':[7,2,6,4,8,5,4,3]}) df.plot() plt.text(2,6,'^_^',fontsize='12') plt.savefig(r'C:\Users\penghuanhuan\Desktop\haha.png',dpi=400,bbox_inches='tight',facecolor='red',edgecolor='yellow') print('finished')
?
四、圖表各對象
figure相當于一塊畫板,ax是畫板中的圖表,一個figure畫板中可以有多個圖表。
創建figure對象:
plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=Figure, clear=False, **kwargs )
如果不設置figure對象,在調用plot時會自動生成一個并且生成其中的一個子圖,且所有plot生成的圖表都顯示在一個圖表上面。
num:指定為畫板中的第幾個圖表,在同一段代碼中,相同figure對象的不同num,各自生成一個圖表,相同figure對象的相同num和不同figure對象的相同num,均生成在一個圖標上。
figsize:圖表的大小,即長和寬,元組形式(m,n)
dpi:分辨率
?
1.創建子圖方法1
①通過plt生成figure對象
②通過figure對象的add_subplot(m,n,p)創建子圖,表示生成m*n個子圖,并選擇第p個子圖,子圖的順序由左到右由上到下
③在子圖上繪制圖表


#子圖 fig = plt.figure(figsize = (8,4),facecolor = 'lightgray') #創建figure對象 ax1 = fig.add_subplot(2,2,1) #創建一個2*2即4個子圖,并選擇第1個子圖,參數也可以直接寫成221# ax1 =plt.subplot(2,2,1) 也可以使用這種方式添加子圖 plt.plot(np.random.rand(20),'k--') #在子圖上1繪制圖表 plt.plot(np.random.rand(20),'b--') #在子圖上1繪制圖表 # ax1.plot(np.random.rand(20),'b--') ax2 = fig.add_subplot(2,2,3) #選擇第3個子圖 ax2.scatter(np.random.rand(100),np.random.rand(100)) #在子圖上3繪制圖表 ax3 = fig.add_subplot(2,2,2) #選擇第2個子圖 ax3.hist(np.random.rand(20))ax4 = fig.add_subplot(2,2,4) #選擇第4個子圖 ax4.plot(pd.DataFrame(np.random.rand(10,2),columns = ['A','B']))
?
?
2.創建子圖方法2
①通過plt的subplots(m,n)方法生成一個figure對象和一個表示figure對象m*n個子圖的二維數組
②通過二維數組選擇子圖并在子圖上繪制圖表


fig,axes = plt.subplots(2,3,figsize = (10,6)) #生成一個figure對象,和一個2*3的二維數組,數組元素為子圖對象 #subplots方法還有參數sharex和sharey,表示是否共享x軸和y軸,默認為False print(fig,type(fig)) #figure對象 print(axes,type(axes))ax1 = axes[0][1] #表示選擇第1行第2個子圖 ax1.plot(np.random.rand(20))ax2 = axes[1,0] #表示選擇第2行第1個子圖 ax2.plot(np.arange(10))plt.subplots_adjust(wspace=0.2,hspace=0.3) #調整子圖之間的間隔寬、間隔高占比
?
3.子圖的創建方法3
在創建plot的時候添加參數subplot=True即可
df.plot(style='--ro',subplots=True,figsize=(10,8),layout=(2,2),sharex=False,sharey=True)
subplots:默認為False,在一張圖表上顯示,True則會拆分為子圖
layout:子圖的排列方式,即幾行幾列
sharex:默認為True
sharey:默認為False
df = pd.DataFrame(np.random.rand(100,4)) df.plot(style='--ro') df.plot(style='--ro',subplots=True,figsize=(10,8),layout=(2,2),sharex=False,sharey=True)
?
?
?
顯示漢字問題請參考https://www.cnblogs.com/kuxingseng95/p/10021788.html