matplotlib 是Python最著名的繪圖庫,它提供了一整套和matlab類似的命令API,十分適合交互式地行製圖。並且也能夠方便地將它做爲繪圖控件,嵌入GUI應用程序中。html
它的文檔至關完備,而且Gallery頁面中有上百幅縮略圖,打開以後都有源程序。所以若是你須要繪製某種類型的圖,只須要在這個頁面中瀏覽/複製/粘貼一下,基本上都能搞定。python
在Linux下比較著名的數據圖工具還有gnuplot,這個是免費的,Python有一個包能夠調用gnuplot,可是語法比較不習慣,並且畫圖質量不高。linux
而 Matplotlib則比較強:Matlab的語法、python語言、latex的畫圖質量(還可使用內嵌的latex引擎繪製的數學公式)。express
Matplotlib.pyplot快速繪圖canvas
matplotlib其實是一套面向對象的繪圖庫,它所繪製的圖表中的每一個繪圖元素,例如線條Line2D、文字Text、刻度等在內存中都有一個對象與之對應。數組
爲了方便快速繪圖matplotlib經過pyplot模塊提供了一套和MATLAB相似的繪 圖API,將衆多繪圖對象所構成的複雜結構隱藏在這套API內部。咱們只須要調用pyplot模塊所提供的函數就能夠實現快速繪圖以及設置圖表的各類細 節。pyplot模塊雖然用法簡單,但不適合在較大的應用程序中使用。dom
爲了將面向對象的繪圖庫包裝成只使用函數的調用接口,pyplot模塊的內部保存了當前圖表以 及當前子圖等信息。當前的圖表和子圖可使用plt.gcf()和plt.gca()得到,分別表示"Get Current Figure"和"Get Current Axes"。在pyplot模塊中,許多函數都是對當前的Figure或Axes對象進行處理,好比說:ide
plt.plot()實際上會經過plt.gca()得到當前的Axes對象ax,而後再調用ax.plot()方法實現真正的繪圖。函數
能夠在Ipython中輸入相似"plt.plot??"的命令查看pyplot模塊的函數是如何對各類繪圖對象進行包裝的。工具
matplotlib所繪製的圖表的每一個組成部分都和一個對象對應,咱們能夠經過調用這些對象的屬性設置方法set_*()或者pyplot模塊的屬性設置函數setp()設置它們的屬性值。
由於matplotlib其實是一套面向對象的繪圖庫,所以也能夠直接獲取對象的屬性
繪製一幅圖須要對許多對象的屬性進行配置,例如顏色、字體、線型等等。咱們在繪圖時,並無逐一對這些屬性進行配置,許多都直接採用了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)
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()
matplotlib的缺省配置文件中所使用的字體沒法正確顯示中文。爲了讓圖表能正確顯示中文,能夠有幾種解決方案。
matplotlib API包含有三層,Artist層處理全部的高層結構,例如處理圖表、文字和曲線等的繪製和佈局。一般咱們只和Artist打交道,而不須要關心底層的繪製細節。
直接使用Artists建立圖表的標準流程以下:
import matplotlib.pyplot as plt
X1 = range(0, 50)
Y1 = [num**2 for num in X1] # y = x^2
X2 = [0, 1]
Y2 = [0, 1] # y = x
Fig = plt.figure(figsize=(8,4)) # Create a `figure' instance
Ax = Fig.add_subplot(111) # Create a `axes' instance in the figure
Ax.plot(X1, Y1, X2, Y2) # Create a Line2D instance in the axes
Fig.show()
Fig.savefig("test.pdf")
參考:
《Python科學計算》(Numpy視頻) matplotlib-繪製精美的圖表(快速繪圖)(面向對象繪圖)(深刻淺出適合系統學習)
什麼是 Matplotlib (主要講面向對象繪圖,對於新手可能有點亂)
Matplotlib.pylab快速繪圖
>>> import pylab as pl
1 安裝numpy和matplotlib
>>> import numpy
>>> numpy.__version__
>>> import matplotlib
>>> matplotlib.__version__
2 兩種經常使用圖類型:Line and scatter plots(使用plot()命令), histogram(使用hist()命令)
2.1 折線圖&散點圖 Line and scatter plots
2.1.1 折線圖 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
2.1.2 散點圖 Scatter plots
把pl.plot(x, y)改爲pl.plot(x, y, 'o')便可,下圖的藍色版本
2.2 美化 Making things look pretty
2.2.1 線條顏色 Changing the line color
紅色:把pl.plot(x, y, 'o')改爲pl.plot(x, y, ’or’)
2.2.2 線條樣式 Changing the line style
虛線:plot(x,y, '--')
2.2.3 marker樣式 Changing the marker style
藍色星型markers:plot(x,y, ’b*’)
2.2.4 圖和軸標題以及軸座標限度 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
2.2.5 在一個座標系上繪製多個圖 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
2.2.6 圖例 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(x^2)$"),直接調用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
2.3 直方圖 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()
若是不想要黑色輪廓能夠改成pl.hist(data, histtype=’stepfilled’)
2.3.1 自定義直方圖bin寬度 Setting the width of the histogram bins manually
增長這兩行
bins = np.arange(-5., 16., 1.) #浮點數版本的range
pl.hist(data, bins, histtype=’stepfilled’)
3 同一畫板上繪製多幅子圖 Plotting more than one axis per canvas
若是須要同時繪製多幅圖表的話,能夠是給figure傳遞一個整數參數指定圖標的序號,若是所指定
序號的繪圖對象已經存在的話,將不建立新的對象,而只是讓它成爲當前繪圖對象。
fig1 = pl.figure(1)
pl.subplot(211)
subplot(211)把繪圖區域等分爲2行*1列共兩個區域, 而後在區域1(上區域)中建立一個軸對象. pl.subplot(212)在區域2(下區域)建立一個軸對象。
You can play around with plotting a variety of layouts. For example, Fig. 11 is created using the following commands:
f1 = pl.figure(1)
pl.subplot(221)
pl.subplot(222)
pl.subplot(212)
當繪圖對象中有多個軸的時候,能夠經過工具欄中的Configure Subplots按鈕,交互式地調節軸之間的間距和軸與邊框之間的距離。若是但願在程序中調節的話,能夠調用subplots_adjust函數,它有 left, right, bottom, top, wspace, hspace等幾個關鍵字參數,這些參數的值都是0到1之間的小數,它們是以繪圖區域的寬高爲1進行正規化以後的座標或者長度。
pl.subplots_adjust(left=0.08, right=0.95, wspace=0.25, hspace=0.45)
4 繪製文件中的數據Plotting data contained in files
4.1 從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()
4.2 寫入數據到文件 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
# ’\t’ means ’tab’
# ’\n’ means ’newline’
# ’str()’ means you are converting the quantity in brackets to a string type
txt = str(x[i]) + ’\t’ + str(y[i]) + ’ \n’
# write the txt to the file
file.write(txt)
# Close your file
file.close()
這部分是翻譯自:Python Plotting Beginners Guide
對LaTeX數學公式的支持
Matlplotlib對LaTeX有必定的支持,若是記得使用raw字符串語法會很天然:
xlabel(r"$\frac{x^2}{y^4}$")
在matplotlib裏面,可使用LaTex的命令來編輯公式,只須要在字符串前面加一個「r」便可
Here is a simple example:
# plain text
plt.title('alpha > beta')
produces 「alpha > beta」.
Whereas this:
# math text
plt.title(r'$\alpha > \beta$')
produces "".
這裏給你們看一個簡單的例子。
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 = r"$y = \frac{1}{2\sigma_1^2}, c=5,\sigma_1=-2$")
ax.legend()
ax.set_xlabel(r"x")
ax.set_ylabel(r"y")
程序執行結果如圖3所示,這其實是一個power-law的例子,有興趣的朋友能夠繼續google之。
再看一個《用Python作科學計算》中的簡單例子,下面的兩行程序經過調用plot函數在當前的繪圖對象中進行繪圖:
plt.plot(x,y,label="$sin(x)$",color="red",linewidth=2)
plt.plot(x,z,"b--",label="$cos(x^2)$")
plot函數的調用方式很靈活,第一句將x,y數組傳遞給plot以後,用關鍵字參數指定各類屬性:
詳細的能夠參考matplotlib官方教程:
Writing mathematical expressions
有幾個問題: