Python進階(三十九)-數據可視化の使用matplotlib進行繪圖分析數據

      網友投稿 1306 2025-04-01

      #Python進階(三十九)-數據可視化の使用matplotlib進行繪圖分析數據

      matplotlib 是python最著名的繪圖庫,它提供了一整套和matlab相似的命令API,十分適合交互式地進行制圖。而且也可以方便地將它作為繪圖控件,嵌入GUI應用程序中。

      它的文檔相當完備,并且 Gallery頁面 中有上百幅縮略圖,打開之后都有源程序。因此如果你需要繪制某種類型的圖,只需要在這個頁面中瀏覽/復制/粘貼一下,基本上都能搞定。

      在Linux下比較著名的數據圖工具還有gnuplot,這個是免費的,Python有一個包可以調用gnuplot,但是語法比較不習慣,而且畫圖質量不高。

      而 Matplotlib則比較強:Matlab的語法、python語言、latex的畫圖質量(還可以使用內嵌的latex引擎繪制的數學公式)。

      matplotlib中的快速繪圖的函數庫可以通過如下語句載入:

      import matplotlib.pyplot as plt

      1

      matplotlib還提供了名為pylab的模塊,其中包括了許多numpy和pyplot中常用的函數,方便用戶快速進行計算和繪圖,可以用于IPython中的快速交互式使用。

      接下來調用figure創建一個繪圖對象,并且使它成為當前的繪圖對象。

      plt.figure(figsize=(8,4))

      1

      也可以不創建繪圖對象直接調用接下來的plot函數直接繪圖,matplotlib會為我們自動創建一個繪圖對象。如果需要同時繪制多幅圖表的話,可以是給figure傳遞一個整數參數指定圖標的序號,如果所指定序號的繪圖對象已經存在的話,將不創建新的對象,而只是讓它成為當前繪圖對象。

      通過figsize參數可以指定繪圖對象的寬度和高度,單位為英寸;dpi參數指定繪圖對象的分辨率,即每英寸多少個像素,缺省值為80。因此本例中所創建的圖表窗口的寬度為880 = 640像素。

      但是用工具欄中的保存按鈕保存下來的png圖像的大小是800400像素。這是因為保存圖表用的函數savefig使用不同的DPI配置,savefig函數也有一個dpi參數,如果不設置的話,將使用matplotlib配置文件中的配置,此配置可以通過如下語句進行查看:

      import matplotlib matplotlib.rcParams[savefig.dpi]

      1

      2

      下面的兩行程序通過調用plot函數在當前的繪圖對象中進行繪圖:

      plt.plot(years, price, 'b*')#,label=$cos(x^2)$) plt.plot(years, price, 'r')

      1

      2

      plot函數的調用方式很靈活,第一句將x,y數組傳遞給plot之后,用關鍵字參數指定各種屬性:

      label : 給所繪制的曲線一個名字,此名字在圖示(legend)中顯示。只要在字符串前后添加$符號,matplotlib就會使用其內嵌的latex引擎繪制的數學公式。

      color : 指定曲線的顏色

      linewidth : 指定曲線的寬度

      第一句直接通過第三個參數b–指定曲線的顏色和線型,這個參數稱為格式化參數,它能夠通過一些易記的符號快速指定曲線的樣式。其中b表示藍色,–表示線型為虛線。

      在IPython中輸入 plt.plot? 可以查看格式化字符串的詳細配置。

      接下來通過一系列函數設置繪圖對象的各個屬性:

      plt.xlabel(years(+2000)) plt.ylabel(housing average price(*2000 yuan)) plt.ylim(0, 15) plt.title('line_regression & gradient decrease') plt.legend()

      1

      2

      3

      4

      5

      xlabel : 設置X軸的文字

      ylabel : 設置Y軸的文字

      title : 設置圖表的標題

      ylim : 設置Y軸的范圍

      legend : 顯示圖示

      最后調用plt.show()顯示出我們創建的所有繪圖對象。

      ##配置屬性

      matplotlib所繪制的圖的每個組成部分都對應有一個對象,我們可以通過調用這些對象的屬性設置方法set_*或者pyplot的屬性設置函數setp設置其屬性值。例如plot函數返回一個 matplotlib.lines.Line2D 對象的列表,下面的例子顯示如何設置Line2D對象的屬性:

      import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1) line, = plt.plot(x, x*x) # plot返回一個列表,通過line,獲取其第一個元素 # 調用Line2D對象的set_*方法設置屬性值 line.set_antialiased(False) # 同時繪制sin和cos兩條曲線,lines是一個有兩個Line2D對象的列表 lines = plt.plot(x, np.sin(x), x, np.cos(x)) # 調用setp函數同時配置多個Line2D對象的多個屬性值 plt.setp(lines, color=r, linewidth=2.0)

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      這段例子中,通過調用Line2D對象line的set_antialiased方法,關閉對象的反鋸齒效果。或者通過調用plt.setp函數配置多個Line2D對象的顏色和線寬屬性。

      同樣我們可以通過調用Line2D對象的get_*方法,或者plt.getp函數獲取對象的屬性值:

      line.get_linewidth() plt.getp(lines[0], color) # 返回color屬性 plt.getp(lines[1]) # 輸出全部屬性 alpha = 1.0 animated = False antialiased or aa = True axes = Axes(0.125,0.1;0.775x0.8)

      1

      2

      3

      4

      5

      6

      7

      注意getp函數只能對一個對象進行操作,它有兩種用法:

      指定屬性名:返回對象的指定屬性的值

      不指定屬性名:打印出對象的所有屬性和其值

      matplotlib的整個圖表為一個Figure對象,此對象在調用plt.figure函數時返回,我們也可以通過plt.gcf函數獲取當前的繪圖對象:

      f = plt.gcf() plt.getp(f) alpha = 1.0 animated = False

      1

      2

      3

      4

      Figure對象有一個axes屬性,其值為AxesSubplot對象的列表,每個AxesSubplot對象代表圖表中的一個子圖,前面所繪制的圖表只包含一個子圖,當前子圖也可以通過plt.gca獲得:

      plt.getp(f, axes) plt.gca()

      1

      2

      用plt.getp可以發現AxesSubplot對象有很多屬性,例如它的lines屬性為此子圖所包括的 Line2D 對象列表:

      alllines = plt.getp(plt.gca(), lines) alllines[0] == line # 其中的第一條曲線就是最開始繪制的那條曲線

      1

      2

      通過這種方法我們可以很容易地查看對象的屬性和它們之間的包含關系,找到需要配置的屬性。

      ##配置文件

      繪制一幅圖需要對許多對象的屬性進行配置,例如顏色、字體、線型等等。我們在繪圖時,并沒有逐一對這些屬性進行配置,許多都直接采用了matplotlib的缺省配置。

      matplotlib將這些缺省配置保存在一個名為“matplotlibrc”的配置文件中,通過修改配置文件,我們可以修改圖表的缺省樣式。配置文件的讀入可以使用rc_params(),它返回一個配置字典;在matplotlib模塊載入時會調用rc_params(),并把得到的配置字典保存到rcParams變量中;matplotlib將使用rcParams字典中的配置進行繪圖;用戶可以直接修改此字典中的配置,所做的改變會反映到此后創建的繪圖元素。

      ##繪制多子圖(快速繪圖)

      Matplotlib 里的常用類的包含關系為 Figure -> Axes -> (Line2D, Text, etc.)一個Figure對象可以包含多個子圖(Axes),在matplotlib中用Axes對象表示一個繪圖區域,可以理解為子圖。

      可以使用subplot()快速繪制包含多個子圖的圖表,它的調用形式如下:

      subplot(numRows, numCols, plotNum)

      1

      subplot將整個繪圖區域等分為numRows行* numCols列個子區域,然后按照從左到右,從上到下的順序對每個子區域進行編號,左上的子區域的編號為1。如果numRows,numCols和plotNum這三個數都小于10的話,可以把它們縮寫為一個整數,例如subplot(323)和subplot(3,2,3)是相同的。subplot在plotNum指定的區域中創建一個軸對象。如果新創建的軸和之前創建的軸重疊的話,之前的軸將被刪除。

      subplot()返回它所創建的Axes對象,我們可以將它用變量保存起來,然后用sca()交替讓它們成為當前Axes對象,并調用plot()在其中繪圖。

      ##繪制多圖表(快速繪圖)

      如果需要同時繪制多幅圖表,可以給figure()傳遞一個整數參數指定Figure對象的序號,如果序號所指定的Figure對象已經存在,將不創建新的對象,而只是讓它成為當前的Figure對象。

      import numpy as np import matplotlib.pyplot as plt plt.figure(1) # 創建圖表1 plt.figure(2) # 創建圖表2 ax1 = plt.subplot(211) # 在圖表2中創建子圖1 ax2 = plt.subplot(212) # 在圖表2中創建子圖2 x = np.linspace(0, 3, 100) for i in xrange(5): plt.figure(1) #? # 選擇圖表1 plt.plot(x, np.exp(i*x/3)) plt.sca(ax1) #? # 選擇圖表2的子圖1 plt.plot(x, np.sin(i*x)) plt.sca(ax2) # 選擇圖表2的子圖2 plt.plot(x, np.cos(i*x)) plt.show()

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      ##在圖表中顯示中文

      matplotlib的缺省配置文件中所使用的字體無法正確顯示中文。為了讓圖表能正確顯示中文,可以有幾種解決方案

      在程序中直接指定字體。

      在程序開頭修改配置字典rcParams。

      修改配置文件。

      比較簡便的方式是,中文字符串用unicode格式,例如:u’‘測試中文顯示’’,代碼文件編碼使用utf-8 加上 # coding = utf-8。

      但以上方法只是解決了標題部分顯示中文的問題,并未解決圖例中文顯示的問題。可采用修改配置字典的方式設置圖例顯示中文,代碼如下:

      # 指定中文字體 mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默認字體

      1

      2

      配置好配置字典之后即可實現圖例顯示中文。

      ![這里寫圖片描述](https://img-blog.csdnimg.cn/img_convert/b753f298918e8eff2f45fd7c6abeb162.png) ??matplotlib API包含有三層,Artist層處理所有的高層結構,例如處理圖表、文字和曲線等的繪制和布局。通常我們只和Artist打交道,而不需要關心底層的繪制細節。 ??直接使用Artists創建圖表的標準流程如下:

      創建Figure對象

      用Figure對象創建一個或者多個Axes或者Subplot對象

      調用Axies等對象的方法創建各種簡單類型的Artists

      import matplotlib.pyplot as plt X1 = range(0, 50) # y = x^2 X2 = [0, 1] Y2 = [0, 1] # y = x Y1 = [num**2 for num in X1] # Create a `figure' instance Fig = plt.figure(figsize=(8,4)) # Create a `axes' instance in the figure Ax = Fig.add_subplot(111) # Create a Line2D instance in the axes Ax.plot(X1, Y1, X2, Y2) Fig.show() Fig.savefig(test.pdf)

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      matplotlib還提供了一個名為pylab的模塊,其中包括了許多NumPy和pyplot模塊中常用的函數,方便用戶快速進行計算和繪圖,十分適合在IPython交互式環境中使用。這里使用下面的方式載入pylab模塊:

      import pylab as pl import numpy numpy.__version__ import matplotlib matplotlib.__version__

      1

      2

      3

      4

      5

      ##折線圖 Line plots(關聯一組x和y值的直線)

      import numpy as np import pylab as pl x = [1, 2, 3, 4, 5]# Make an array of x values y = [1, 4, 9, 16, 25]# Make an array of y values for each x value pl.plot(x, y)# use pylab to plot x and y pl.show()# show the plot on the screen

      1

      2

      3

      4

      5

      6

      ##散點圖 Scatter plots

      把pl.plot(x, y)改成pl.plot(x, y, ‘o’)即可,下圖的藍色版本

      ##美化 Making things look pretty

      ###線條顏色 Changing the line color

      紅色:把pl.plot(x, y, ‘o’)改成pl.plot(x, y, ’or’)

      ###線條樣式 Changing the line style

      虛線:plot(x,y, ‘–’)

      ###marker樣式 Changing the marker style

      藍色星型markers:plot(x,y, ’b*’)

      ###圖和軸標題以及軸坐標限度 Plot and axis titles and limits

      import numpy as np import pylab as pl x = [1, 2, 3, 4, 5]# Make an array of x values y = [1, 4, 9, 16, 25]# Make an array of y values for each x value pl.plot(x, y)# use pylab to plot x and y pl.title(’Plot of y vs. x’)# give plot a title pl.xlabel(’x axis’)# make axis labels pl.ylabel(’y axis’) pl.xlim(0.0, 7.0)# set axis limits pl.ylim(0.0, 30.) pl.show()# show the plot on the screen

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      ###在一個坐標系上繪制多個圖 Plotting more than one plot on the same set of axes

      做法是很直接的,依次作圖即可:

      import numpy as np import pylab as pl x1 = [1, 2, 3, 4, 5]# Make x, y arrays for each graph y1 = [1, 4, 9, 16, 25] x2 = [1, 2, 4, 6, 8] y2 = [2, 4, 8, 12, 16] pl.plot(x1, y1, ’r’)# use pylab to plot x and y pl.plot(x2, y2, ’g’) pl.title(’Plot of y vs. x’)# give plot a title pl.xlabel(’x axis’)# make axis labels pl.ylabel(’y axis’) pl.xlim(0.0, 9.0)# set axis limits pl.ylim(0.0, 30.) pl.show()# show the plot on the screen

      1

      2

      3

      4

      5

      6

      7

      Python進階(三十九)-數據可視化の使用matplotlib進行繪圖分析數據

      8

      9

      10

      11

      12

      13

      14

      ###圖例 Figure legends

      pl.legend((plot1, plot2), (’label1, label2’), 'best’, numpoints=1)

      其中第三個參數表示圖例放置的位置:'best’‘upper right’, ‘upper left’, ‘center’, ‘lower left’, ‘lower right’.

      如果在當前figure里plot的時候已經指定了label,如plt.plot(x,z,label=cos(x2)),直接調用plt.legend()就可以了哦。

      import numpy as np import pylab as pl x1 = [1, 2, 3, 4, 5]# Make x, y arrays for each graph y1 = [1, 4, 9, 16, 25] x2 = [1, 2, 4, 6, 8] y2 = [2, 4, 8, 12, 16] plot1 = pl.plot(x1, y1, ’r’)# use pylab to plot x and y : Give your plots names plot2 = pl.plot(x2, y2, ’go’) pl.title(’Plot of y vs. x’)# give plot a title pl.xlabel(’x axis’)# make axis labels pl.ylabel(’y axis’) pl.xlim(0.0, 9.0)# set axis limits pl.ylim(0.0, 30.) pl.legend([plot1, plot2], (’red line’, ’green circles’), ’best’, numpoints=1)# make legend pl.show()# show the plot on the screen

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      ##直方圖 Histograms

      import numpy as np import pylab as pl # make an array of random numbers with a gaussian distribution with # mean = 5.0 # rms = 3.0 # number of points = 1000 data = np.random.normal(5.0, 3.0, 1000) # make a histogram of the data array pl.hist(data) # make plot labels pl.xlabel(’data’) pl.show()

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      如果不想要黑色輪廓可以改為pl.hist(data, histtype=’stepfilled’)

      ###自定義直方圖bin寬度 Setting the width of the histogram bins manually

      增加這兩行

      bins = np.arange(-5., 16., 1.) #浮點數版本的range pl.hist(data, bins, histtype=’stepfilled’)

      1

      2

      ##繪制文件中的數據Plotting data contained in files

      ###從Ascii文件中讀取數據 Reading data from ascii files

      讀取文件的方法很多,這里只介紹一種簡單的方法,更多的可以參考官方文檔和NumPy快速處理數據(文件存取)。

      numpy的loadtxt方法可以直接讀取如下文本數據到numpy二維數組

      ********************************************** # fakedata.txt 0 0 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 0 0 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 ********************************************** import numpy as np import pylab as pl # Use numpy to load the data contained in the file # ’fakedata.txt’ into a 2-D array called data data = np.loadtxt(’fakedata.txt’) # plot the first column as x, and second column as y pl.plot(data[:,0], data[:,1], ’ro’) pl.xlabel(’x’) pl.ylabel(’y’) pl.xlim(0.0, 10.) pl.show()

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      16

      17

      18

      19

      20

      21

      22

      23

      24

      25

      26

      27

      28

      29

      30

      31

      32

      33

      34

      ###寫入數據到文件 Writing data to a text file

      寫文件的方法也很多,這里只介紹一種可用的寫入文本文件的方法,更多的可以參考官方文檔。

      import numpy as np # Let’s make 2 arrays (x, y) which we will write to a file # x is an array containing numbers 0 to 10, with intervals of 1 x = np.arange(0.0, 10., 1.) # y is an array containing the values in x, squared y = x*x print ’x = ’, x print ’y = ’, y # Now open a file to write the data to # ’w’ means open for ’writing’ file = open(’testdata.txt’, ’w’) # loop over each line you want to write to file for i in range(len(x)): # make a string for each line you want to write # ’ ’ means ’tab’ # ’’ means ’newline’ # ’str()’ means you are converting the quantity in brackets to a string type txt = str(x[i]) + ’ ’ + str(y[i]) + ’ ’ # write the txt to the file file.write(txt) # Close your file file.close()

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      16

      17

      18

      19

      20

      21

      22

      ##對LaTeX數學公式的支持

      Matlplotlib對LaTeX有一定的支持,如果記得使用raw字符串語法會很自然:xlabel(rx2y4)

      在matplotlib里面,可以使用LaTex的命令來編輯公式,只需要在字符串前面加一個“r”即可

      這里給大家看一個簡單的例子。

      import matplotlib.pyplot as plt x = arange(1,1000,1) r = -2 c = 5 y = [5*(a**r) for a in x] fig = plt.figure() ax = fig.add_subplot(111) ax.loglog(x,y,label = ry=12σ21,c=5,σ1=?2) ax.legend() ax.set_xlabel(rx) ax.set_ylabel(ry)

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      再看一個《用Python做科學計算》中的簡單例子,下面的兩行程序通過調用plot函數在當前的繪圖對象中進行繪圖:

      plt.plot(x,y,label=sin(x),color=red,linewidth=2) plt.plot(x,z,b--,label=cos(x2))

      1

      2

      ##matplotlib.rcParams屬性字典

      想要它正常工作,在matplotlibrc配置文件中需要設置text.markup = tex。

      如果你希望圖表中所有的文字(包括坐標軸刻度標記)都是LaTeX,需要在matplotlibrc中設置text.usetex = True。如果你使用LaTeX撰寫論文,那么這一點對于使圖表和論文中其余部分保持一致是很有用的。

      ##matplotlib使用小結

      在實際中,我們可能經常會用到對數坐標軸,這時可以用下面的三個函數來實現。

      ax.semilogx(x,y) #x軸為對數坐標軸

      ax.semilogy(x,y) #y軸為對數坐標軸

      ax.loglog(x,y) #雙對數坐標軸

      ##學習資源

      利用matplotlib 進行折線圖,直方圖和餅圖的繪制

      matplotlib圖表中圖例大小及字體相關問題

      matplotlib繪圖庫入門

      http://sebug.net/paper/books/scipydoc/matplotlib_intro.html

      使用 python Matplotlib 庫繪圖

      ![這里寫圖片描述](https://img-blog.csdnimg.cn/img_convert/f9c024e20306fb0e4e3e84a15aab3217.png)

      Python 數據可視化

      版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。

      版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。

      上一篇:Excel表格怎么設置字體大小顏色(excel表格里字體顏色怎么改)
      下一篇:Excle怎樣設置定時器?(如何設置定時器)
      相關文章
      亚洲AV女人18毛片水真多| 亚洲精品麻豆av| 亚洲中文字幕无码中文| 亚洲国产中文字幕在线观看| 亚洲中文字幕久久无码| 久久亚洲国产最新网站| 亚洲国产成人99精品激情在线| 亚洲香蕉免费有线视频| 亚洲国产成人高清在线观看| 亚洲日韩激情无码一区| 亚洲日韩激情无码一区| 亚洲AV无码一区二三区 | 亚洲日韩中文在线精品第一| 亚洲国产成人精品无码区在线网站 | 亚洲国产天堂久久久久久| 亚洲伊人tv综合网色| 国产99久久亚洲综合精品| 亚洲熟女乱色一区二区三区| 亚洲国产精品va在线播放| 亚洲国产成人久久综合碰| 亚洲男女内射在线播放| 亚洲Av无码国产一区二区| 亚洲最大在线视频| 久久精品国产亚洲AV久| 亚洲国产精品一区二区第一页免| 亚洲不卡AV影片在线播放| 亚洲午夜日韩高清一区| 国产亚洲精品国看不卡| 国产亚洲精久久久久久无码77777| 最新精品亚洲成a人在线观看| 亚洲中文字幕日产乱码高清app | 亚洲色大成网站www永久男同 | 亚洲国产精品无码久久九九大片| 亚洲国产精品成人AV在线| 国产亚洲综合久久| 国产午夜亚洲精品理论片不卡| 亚洲中文无韩国r级电影| 国产亚洲3p无码一区二区| 亚洲国产精久久久久久久| 亚洲性一级理论片在线观看| 亚洲色欲色欱wwW在线|