1.Matplotlib簡介及圖表窗口
Matplotlib → 一個python版的matlab繪圖接口,以2D為主,支持python、numpy、pandas基本數據結構,運營高效且有較豐富的圖表庫
https://matplotlib.org/api/pyplot_api.html
title為圖像標題,Axis為坐標軸, Label為坐標軸標注,Tick為刻度線,Tick Label為刻度注釋。
plt.plot( 數組 ) --> 圖表窗口 plt.show( ) 、
% matplotlib inline 嵌入圖表; ---> plt.scatter(x, y)
% matplotlib notebook 可交互窗口;--->s.plot(style = 'k--o',figsize=(10,5))
% matplotlib qt5可交互性控制台; --->>df.hist(figsize=(12,5),color='g',alpha=0.8)
import numpy as np import pandas as pd import matplotlib.pyplot as plt # 圖表窗口1 → plt.show() plt.plot(np.random.rand(10)) plt.show() # 直接生成圖表
# 圖表窗口2 → 魔法函數,嵌入圖表 % matplotlib inline x = np.random.randn(1000) y = np.random.randn(1000) plt.scatter(x,y) # 直接嵌入圖表,不用plt.show() # <matplotlib.collections.PathCollection at ...> 代表該圖表對象
# 圖表窗口3 → 魔法函數,彈出可交互的matplotlib窗口 % matplotlib notebook s = pd.Series(np.random.randn(100)) s.plot(style='k--o', figsize=(10, 5)) # 可交互的matplotlib窗口,不用plt.show() # 可做一定調整
# 圖表窗口4 → 魔法函數,彈出matplotlib控制台 % matplotlib qt5 df = pd.DataFrame(np.random.rand(50, 2),columns=['A', 'B']) df.hist(figsize=(12, 5), color='g', alpha=0.8) # 可交互性控制台 # 如果已經設置了顯示方式(比如notebook),需要重啟然后再運行魔法函數 # 網頁嵌入的交互性窗口 和 控制台,只能顯示一個 #plt.close() # 關閉窗口 #plt.gcf().clear() # 每次清空圖表內內容
2.圖表的基本元素
圖名,圖例,軸標簽,軸邊界,軸刻度,軸刻度標簽等
plt.title(' ') #圖名 、plt.xlabel('') #x軸標簽、 plt.ylabel('') #y軸標簽 、plt.legend(loc='upper right') #就是圖例的位置 右上
plt.xlim([0, 12])x軸邊界 、plt.ylim([0, 1.5]) y軸邊界 、plt.xticks(range(10))設置x刻度 、plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2])設置y刻度
fig.set_xticklabels("%.1f" %i for i in range(10))x軸刻度標簽 ,使得其顯示1位小數;
fig.set_yticklabels("%.2f" %i for i in [0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2])
xlim范圍只是限制圖表長度,xticks則是決定顯示的標尺,刻度標簽set_xticklabels決定顯示的小數位數;
# 圖名,圖例,軸標簽,軸邊界,軸刻度,軸刻度標簽等 df = pd.DataFrame(np.random.rand(10, 2), columns=['A', 'B']) fig = df.plot(figsize=(6, 4)) # figsize:創建圖表窗口,設置窗口大小; # 創建圖表對象,並賦值與fig
# 圖名,圖例,軸標簽,軸邊界,軸刻度,軸刻度標簽等 df = pd.DataFrame(np.random.rand(10, 2), columns=['A', 'B']) fig = df.plot(figsize=(6, 4)) # figsize:創建圖表窗口,設置窗口大小; #創建圖表對象,並賦值與fig plt.title('Interesting Graph - Check it out') #圖名 plt.xlabel('Plot Number') #x軸標簽 plt.ylabel('Important var') #y軸標簽 plt.legend(loc='upper right') #就是圖例的位置 右上
# 圖例的幾種顯示方式,loc表示位置,分別表示位置。 # 'best' : 0, (only implemented for axes legends)(自適應方式) # '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, plt.xlim([0, 12]) # x軸邊界 plt.ylim([0, 1.5]) # y軸邊界 plt.xticks(range(10)) # 設置x刻度 plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2]) # 設置y刻度 fig.set_xticklabels("%.1f" %i for i in range(10)) # x軸刻度標簽 ,使得其顯示1位小數; 小數的顯示方式變成字符串的形式顯示了。 fig.set_yticklabels("%.2f" %i for i in [0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2]) # y軸刻度標簽,使得y軸顯示后邊再加一位小數,之設置前有一位 # 范圍只限定圖表的長度,刻度則是決定顯示的標尺 → 這里x軸范圍是0-12,但刻度只是0-9,刻度標簽使得其顯示1位小數 # 軸標簽則是顯示刻度的標簽 print(fig, type(fig))
其他元素可視化
弧度制、角度值,正弦/余弦函數
plt.grid(True, linestyle="--", color="gray", linewidth="0.5", axis='x')顯示網格
plt.tick_params(bottom='on',top='off',left='on',right='off')就是4個坐標軸的刻度線是往里凸呢還是凹呢;刻度線的方向matplotlib.rcParams['xtick.direction'] = 'out'
frame.axes.get_xaxis().set_visible(False) x軸上的東西都隱藏了唄
plt.axis('off') # 關閉坐標軸
x = np.linspace(-np.pi,np.pi,256,endpoint = True) #pi值的是圓周率 π math.pi c, s = np.cos(x), np.sin(x) #這里用的是弧度制表示。 plt.plot(x, c) plt.plot(x, s) # plt.grid(True, linestyle="--", color="gray", linewidth="0.5", axis='x') # .grid是創建格網 # 通過ndarry創建圖表 # 顯示網格 # linestyle:線型 # color:顏色 # linewidth:寬度 # axis:x,y,both,顯示x/y/兩者的格網 plt.tick_params(bottom='on',top='off',left='on',right='off') #就是四個軸有刻度凸顯出來,關掉網格線就看出來了 # 刻度顯示 import matplotlib # 這里需要導入matploltib,而不僅僅導入matplotlib.pyplot matplotlib.rcParams['xtick.direction'] = 'out' # 設置刻度的方向: 在里邊是in, 顯示在外邊就是out, 在中間就是inout matplotlib.rcParams['ytick.direction'] = 'inout' frame = plt.gca() frame.axes.get_xaxis().set_visible(False) # False是x/y 軸上的標簽都不顯示出來, frame.axes.get_yaxis().set_visible(False) # plt.axis('off') # 關閉坐標軸
3.圖表的樣式參數
linestyle、style、color、marker
plt.plot([i**2 for i in range(100)],linestyle = '-.' )
linestyle參數 線型
plt.plot([i**2 for i in range(100)], linestyle = '-.') # '-' solid line style # '--' dashed line style # '-.' dash-dot line style # ':' dotted line style
marker參數 線上的點
s.plot(linestyle = '--',marker = '.') 線上的點的形狀唄
s = pd.Series(np.random.randn(100).cumsum()) #.cumsum()是累計求和 s.plot(linestyle = '--', marker = '.') # '.' 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參數顏色
plt.hist(np.random.randn(100),color = 'g',alpha = 0.8) 常用顏色簡寫:red-r, green-g, black-k, blue-b, yellow-y
df.plot(style = '--.', alpha = 0.8, colormap = 'GnBu') colormap顏色板
plt.hist(np.random.randn(100), color = 'g',alpha = 0.8)# alpha:0-1,透明度
df = pd.DataFrame(np.random.randn(1000, 4), columns=list('ABCD')) df = df.cumsum() df.plot(style = '--.', alpha = 0.8, colormap = 'GnBu') # 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, # 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, spectral, # spectral_r ,spring, spring_r, summer, summer_r, terrain, terrain_r, viridis, viridis_r, winter, winter_r # 其他參數見“顏色參數.docx”
style參數,可以包含linestyle,marker,color
ts.plot(style = '--g.',grid=True) linestyle(-)線性,marker(.),color(g)顏色,grid=True是顯示網格線
ts = pd.Series(np.random.randn(1000).cumsum(), index=pd.date_range('1/1/2000', periods=1000)) ts.plot(style = '--g.',grid=True) # style → 風格字符串,這里包括了linestyle(-)線性,marker(.),color(g)顏色 # plot()內也有grid參數
整體風格樣式
psl.use('ggplot')
import matplotlib.style as psl print(plt.style.available) # 查看樣式列表 psl.use('ggplot') ts = pd.Series(np.random.randn(1000).cumsum(), index=pd.date_range('1/1/2000', periods=1000)) ts.plot(style = '--g.',grid = True,figsize=(10,6)) #一旦選用樣式后,所有圖表都會有樣式,重啟后才能關掉
所有的樣式列表--->
['seaborn-bright', 'seaborn-notebook', 'seaborn-darkgrid', 'seaborn-ticks', 'seaborn-poster', 'seaborn-dark', 'grayscale', 'fivethirtyeight',
'seaborn-paper', 'seaborn-whitegrid', 'seaborn-deep', 'ggplot', 'classic', 'bmh', 'dark_background', 'seaborn-colorblind', 'seaborn-white',
'seaborn-muted', 'seaborn-dark-palette', 'seaborn-talk', 'seaborn-pastel']
4.刻度、注解、圖表輸出
主刻度、次刻度
刻度
subplot(2,2,1) 前面倆參數指定的是一個畫板被分割成的行和列,后面一個參數則指的是當前正在繪制的編號!
ax.xaxis.set_major_locator(xmajorLocator)設置x軸主刻度、 xmajorLocator = MultipleLocator(20) 將x主刻度標簽設置為20的倍數
ax.xaxis.set_major_formatter(xmajorFormatter)設置x軸標簽文本格式 、 xmajorFormatter = FormatStrFormatter('%.0f')設置x軸標簽文本的格式
ax.xaxis.set_minor_locator(xminorLocator)設置x軸次刻度、 xminorLocator = MultipleLocator(5) # 將x軸次刻度標簽設置為5的倍數
ax.xaxis.grid(True, which='majpr') #x坐標軸的網格使用(就是縱橫交錯的網格線)主刻度 both、minor(只顯示次刻度)、majpr(只顯示主刻度)
ax.xaxis.set_major_formatter(plt.NullFormatter()) 刪除x坐標軸的刻度顯示
from matplotlib.ticker import MultipleLocator, FormatStrFormatter t = np.arange(0.0, 100.0, 1) s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01) ax = plt.subplot(111) #注意:一般都在ax中設置,不再plot中設置 plt.plot(t,s,'--*') plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'both') # 網格 #plt.legend() # 圖例
xmajorLocator = MultipleLocator(20) # 將x主刻度標簽設置為10的倍數 xmajorFormatter = FormatStrFormatter('%.0f') # 設置x軸標簽文本的格式 xminorLocator = MultipleLocator(5) # 將x軸次刻度標簽設置為5的倍數 ymajorLocator = MultipleLocator(0.5) # 將y軸主刻度標簽設置為0.5的倍數 ymajorFormatter = FormatStrFormatter('%.1f') # 設置y軸標簽文本的格式 yminorLocator = MultipleLocator(0.1) # 將此y軸次刻度標簽設置為0.1的倍數 ax.xaxis.set_major_locator(xmajorLocator) # 設置x軸主刻度 ax.xaxis.set_major_formatter(xmajorFormatter) # 設置x軸標簽文本格式 ax.xaxis.set_minor_locator(xminorLocator) # 設置x軸次刻度 ax.yaxis.set_major_locator(ymajorLocator) # 設置y軸主刻度 ax.yaxis.set_major_formatter(ymajorFormatter) # 設置y軸標簽文本格式 ax.yaxis.set_minor_locator(yminorLocator) # 設置y軸次刻度ax.xaxis.grid(True, which='majpr') #x坐標軸的網格使用(就是縱橫交錯的網格線)主刻度 both、minor(只顯示次刻度)、majpr(只顯示主刻度) ax.yaxis.grid(True, which='minor') #y坐標軸的網格使用次刻度 # which:格網顯示 #刪除坐標軸的刻度顯示 #ax.yaxis.set_major_locator(plt.NullLocator()) # ax.xaxis.set_major_formatter(plt.NullFormatter())
注解
plt.text(5,0.5,'hello',fontsize=10) 參數是注釋在坐標系中的位置和大小:(5,0.5)
df = pd.DataFrame(np.random.randn(10,2)) df.plot(style = '--o') plt.text(5,0.5,'hello',fontsize=10) # 注解 → 橫坐標,縱坐標,注解字符串
圖表輸出
plt.savefig('C:/Users/Administrator/Desktop/pic.png',
dpi=400, #分表率;
bbox_inches = 'tight', #剪出周圍的空白
facecolor = 'g', #圖像的背景色
edgecolor = 'b') #圖片的edgecolor
df = pd.DataFrame(np.random.randn(1000, 4), columns=list('ABCD')) df = df.cumsum() df.plot(style = '--.',alpha = 0.5) plt.legend(loc = 'upper right') plt.savefig('C:/Users/Administrator/Desktop/pic.png', dpi=400, bbox_inches = 'tight', facecolor = 'g', edgecolor = 'b') # 可支持png,pdf,svg,ps,eps…等,以后綴名來指定 # dpi是分辨率 # bbox_inches:圖表需要保存的部分。如果設置為‘tight’,則嘗試剪除圖表周圍的空白部分。 # facecolor,edgecolor: 圖像的背景色,默認為‘w’(白色)
5.子圖
在matplotlib中,整個圖像為一個Figure對象
在Figure對象中可以包含一個或者多個Axes對象
每個Axes(ax)對象都是一個擁有自己坐標系統的繪圖區域
plt.figure, plt.subplot
# plt.figure() 繪圖對象 # plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, # frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, **kwargs) fig1 = plt.figure(num=1,figsize=(4,2)) plt.plot(np.random.rand(50).cumsum(),'k--') fig2 = plt.figure(num=2,figsize=(4,2)) plt.plot(50-np.random.rand(50).cumsum(),'k--') # num:圖表序號,如果他們兩個的序號一樣,曲線就會顯示在一張圖片里邊;如果把num都去掉,則跟num=1和num=2是一樣的效果。 # figsize:圖表大小 # 當我們調用plot時,如果設置plt.figure(),則會自動調用figure()生成一個figure, 嚴格的講,是生成subplots(111)
fig.add_subplot(2,2,1)生成創建好的圖表figure() 2*2的矩陣表格,第1個個位置 、 plt.plot(np.random.rand(50).cumsum(),'k--')往上邊畫線,填圖
# 子圖創建1 - 先建立子圖然后填充圖表 fig = plt.figure(figsize=(10,6),facecolor = 'gray') ax1 = fig.add_subplot(2,2,1) # 第一行的左圖 plt.plot(np.random.rand(50).cumsum(),'k--') plt.plot(np.random.randn(50).cumsum(),'b--') # 先創建圖表figure,然后生成子圖,(2,2,1)代表創建2*2的矩陣表格,然后選擇第一個,順序是從左到右從上到下 # 創建子圖后繪制圖表,會繪制到最后一個子圖 ax2 = fig.add_subplot(2,2,2) # 第一行的右圖 ax2.hist(np.random.rand(50),alpha=0.5) ax4 = fig.add_subplot(2,2,4) # 第二行的右圖 df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd']) ax4.plot(df2,alpha=0.5,linestyle='--',marker='.') # 也可以直接在子圖后用圖表創建函數直接生成圖表
---->
[<matplotlib.lines.Line2D at 0x13bbb240>, <matplotlib.lines.Line2D at 0x13bbb390>, <matplotlib.lines.Line2D at 0x13bbb5f8>, <matplotlib.lines.Line2D at 0x13bbb780>]
fig, axes = plt.subplots(2,3,figsize=(10,4)) 創建2*3個fig圖,2*3個數組。--->> ax1 = axes[0,1] ---> ax1.plot(ts) 在[0,1]的圖中繪線
# 子圖創建2 - 創建一個新的figure,並返回一個subplot對象的numpy數組 → plt.subplot fig,axes = plt.subplots(2,3,figsize=(10,4)) ts = pd.Series(np.random.randn(1000).cumsum()) print(axes, axes.shape, type(axes)) # 生成圖表對象的數組,2行3列的數組 print(fig,type(fig)---->>> Figure(720x288) <class 'matplotlib.figure.Figure'>
ax1 = axes[0,1] #表示在第一行第二個圖片繪制圖線。 ax1.plot(ts) ---------------->>>>>>>>>> [[<matplotlib.axes._subplots.AxesSubplot object at 0x000000000BB5A4A8> <matplotlib.axes._subplots.AxesSubplot object at 0x000000000C08B240> <matplotlib.axes._subplots.AxesSubplot object at 0x000000000C0D6550>] [<matplotlib.axes._subplots.AxesSubplot object at 0x000000000C10CDD8> <matplotlib.axes._subplots.AxesSubplot object at 0x000000000C15B160> <matplotlib.axes._subplots.AxesSubplot object at 0x000000000C190DA0>]] (2, 3) <class 'numpy.ndarray'>
plt.subplots( ),參數調整,是否共享坐標軸
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)# sharex,sharey:是否共享x,y刻度
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)# sharex,sharey:是否共享x,y刻度 for i in range(2): for j in range(2): axes[i, j].hist(np.random.randn(500), color='k', alpha=0.5) plt.subplots_adjust(wspace=0,hspace=0) # wspace,hspace:用於控制寬度和高度的百分比,比如subplot之間的間距
df.plot(style = '--.', alpha=0.4, grid=True, figsize = (8, 8),
subplots = True, #為False時是繪制到了一張圖上面
layout = (2,3),# 2*3的矩陣填充圖
sharex = False) #不共享x軸
plt.subplots_adjust(wspace=0,hspace=0.2) ##wspace是子圖之間的橫向間距,hspace是子圖之間的豎直間距。
# 子圖創建3 - 多系列圖,分別繪制 df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns = list('ABCD')) df = df.cumsum() df.plot(style = '--.', alpha=0.4, grid=True, figsize = (8, 8), subplots = True, #為False時是繪制到了一張圖上面 layout = (2,3), sharex = False) plt.subplots_adjust(wspace=0,hspace=0.2) ##wspace是子圖之間的橫向間距,hspace是子圖之間的豎直間距。 # plt.plot()基本圖表繪制函數 → subplots,是否分別繪制系列(子圖) # layout:繪制子圖矩陣,按順序填充