本文做爲學習過程當中對matplotlib一些經常使用知識點的整理,方便查找。php
最簡單的入門是從類 MATLAB API 開始,它被設計成兼容 MATLAB 繪圖函數。html
from pylab import * from numpy import * x = linspace(0, 5, 10) y = x ** 2 figure() plot(x, y, 'r') xlabel('x') ylabel('y') title('title')
建立子圖,選擇繪圖用的顏色與描點符號:python
subplot(1,2,1) plot(x, y, 'r--') subplot(1,2,2) plot(y, x, 'g*-');
linspace表示在0到5之間用10個點表示,plot的第三個參數表示畫線的顏色與樣式nginx
此類 API 的好處是能夠節省你的代碼量,可是咱們並不鼓勵使用它處理複雜的圖表。處理複雜圖表時, matplotlib 面向對象 API 是一個更好的選擇。git
使用面向對象API的方法和以前例子裏的看起來很相似,不一樣的是,咱們並不建立一個全局實例,而是將新建實例的引用保存在 fig 變量中,若是咱們想在圖中新建一個座標軸實例,只須要 調用 fig 實例的 add_axes 方法:github
import matplotlib.pyplot as plt from pylab import * x = linspace(0, 5, 10) y = x ** 2 fig = plt.figure() axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1) axes.plot(x, y, 'r') axes.set_xlabel('x') axes.set_ylabel('y') axes.set_title('title') plt.show()
儘管會寫更多的代碼,好處在於咱們對於圖表的繪製有了徹底的控制權,能夠很容易地多加一個座標軸到圖中:api
import matplotlib.pyplot as plt from pylab import * x = linspace(0, 5, 10) y = x ** 2 fig = plt.figure() axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1) axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes axes.plot(x, y, 'r') axes.set_xlabel('x') axes.set_ylabel('y') axes.set_title('title') # insert axes2.plot(y, x, 'g') axes2.set_xlabel('y') axes2.set_ylabel('x') axes2.set_title('insert title'); plt.show()
若是咱們不在乎座標軸在圖中的排放位置️,那麼就可使用matplotlib的佈局管理器了,我最喜歡的是subplots,使用方式以下:ruby
import matplotlib.pyplot as plt from pylab import * x = linspace(0, 5, 10) y = x ** 2 fig, axes = plt.subplots(nrows=1, ncols=2) for ax in axes: ax.plot(x, y, 'r') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('title') fig.tight_layout() plt.show()
圖表尺寸,長寬比 與 DPIapp
在建立 Figure 對象的時候,使用figsize 與 dpi 參數可以設置圖表尺寸與DPI, 建立一個800*400像素,每英寸100像素的圖就能夠這麼作:dom
fig = plt.figure(figsize=(8,4), dpi=100)
<matplotlib.figure.Figure at 0x4cbd390>
一樣的參數也能夠用在佈局管理器上:
fig, axes = plt.subplots(figsize=(12,3)) axes.plot(x, y, 'r') axes.set_xlabel('x') axes.set_ylabel('y') axes.set_title('title');
保存圖表
可使用 savefig 保存圖表
fig.savefig("filename.png") 這裏咱們也能夠有選擇地指定DPI,而且選擇不一樣的輸出格式: fig.savefig("filename.png", dpi=200)
有哪些格式?哪一種格式能得到最佳質量?
Matplotlib 能夠生成多種格式的高質量圖像,包括PNG,JPG,EPS,SVG,PGF 和 PDF。若是是科學論文的話,我建議儘可能使用pdf格式。 (pdflatex 編譯的 LaTeX 文檔使用 includegraphics 命令就能包含 PDF 文件)。 一些狀況下,PGF也是一個很好的選擇。
如今咱們已經介紹瞭如何建立圖表畫布以及如何添加新的座標軸實例,讓咱們看一看如何加上標題,軸標和圖例
標題
每個座標軸實例均可以加上一個標題,只需調用座標軸實例的 set_title 方法:
ax.set_title("title");
軸標
相似的, set_xlabel 與 set_ylabel 能夠設置座標軸的x軸與y軸的標籤。
ax.set_xlabel("x") ax.set_ylabel("y");
圖例
有兩種方法在圖中加入圖例。一種是調用座標軸對象的 legend 方法,傳入與以前定義的幾條曲線相對應地圖例文字的 列表/元組:
ax.legend([「curve1」, 「curve2」, 「curve3」]);
不過這種方式容易出錯,好比增長了新的曲線或者移除了某條曲線。更好的方式是在調用 plot方法時使用 label=」label text」 參數,再調用 legend 方法加入圖例:
ax.plot(x, x**2, label="curve1") ax.plot(x, x**3, label="curve2") ax.legend();
legend 還有一個可選參數 loc 決定畫出圖例的位置,詳情見:http://matplotlib.org/users/legend_guide.html#legend-location
最經常使用的值以下:
ax.legend(loc=0) # let matplotlib decide the optimal location ax.legend(loc=1) # upper right corner ax.legend(loc=2) # upper left corner ax.legend(loc=3) # lower left corner ax.legend(loc=4) # lower right corner # .. many more options are available => <matplotlib.legend.Legend at 0x4c863d0>
下面這個例子同時包含了標題,軸標,與圖例的用法:
import matplotlib.pyplot as plt from pylab import * x = linspace(0, 5, 10) y = x ** 2 fig, ax = plt.subplots() ax.plot(x, x**2, label="y = x**2") ax.plot(x, x**3, label="y = x**3") ax.legend(loc=2); # upper left corner ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('title'); plt.show()
格式化文本,LaTeX,字體大小,字體類型
Matplotlib 對 LaTeX 提供了很好的支持。咱們只須要將 LaTeX 表達式封裝在 符號內,就可以在圖的任何文本中顯示了,比如「符號內,就能夠在圖的任何文本中顯示了,好比「
不過這裏咱們會遇到一些小問題,在 LaTeX 中咱們經常會用到反斜槓,好比 \alpha 來產生符號 αα
import matplotlib.pyplot as plt from pylab import * x = linspace(0, 5, 10) y = x ** 2 fig, ax = plt.subplots() ax.plot(x, x**2, label=r"$y = \alpha^2$") ax.plot(x, x**3, label=r"$y = \alpha^3$") ax.legend(loc=2) # upper left corner ax.set_xlabel(r'$\alpha$', fontsize=18) ax.set_ylabel(r'$y$', fontsize=18) ax.set_title('title'); plt.show()
咱們能夠更改全局字體大小或者類型:
from matplotlib import rcParams rcParams.update({'font.size': 18, 'font.family': 'serif'})
STIX 字體是一種好選擇:
matplotlib.rcParams.update({'font.size': 18, 'font.family': 'STIXGeneral', 'mathtext.fontset': 'stix'})
咱們也能夠將圖中的文本全用 Latex 渲染:
matplotlib.rcParams.update({'font.size': 18, 'text.usetex': True})
設置顏色,線寬 與 線型
顏色
有了matplotlib,咱們就有不少方法可以定義線的顏色和不少其餘圖形元素。首先,咱們可使用類MATLAB語法,’b’ 表明藍色,’g’ 表明綠色,依此類推。matplotlib同時也支持 MATLAB API 選擇線型所使用的方式:好比 ‘b.-‘ 意味着藍線標着點:
# MATLAB style line color and style ax.plot(x, x**2, 'b.-') # blue line with dots ax.plot(x, x**3, 'g--') # green dashed line fig => [<matplotlib.lines.Line2D at 0x4985810>]
咱們也能夠以顏色的名字或者RGB值選擇顏色,alpha參數決定了顏色的透明度:
fig, ax = plt.subplots()
ax.plot(x, x+1, color="red", alpha=0.5) # half-transparant red ax.plot(x, x+2, color="#1155dd") # RGB hex code for a bluish color ax.plot(x, x+3, color="#15cc55") # RGB hex code for a greenish color fig => [<matplotlib.lines.Line2D at 0x4edbd10>]
線與描點風格
linewidth 或是 lw 參數改變線寬。 linestyle 或是 ls 參數改變線的風格。
fig, ax = plt.subplots(figsize=(12,6)) ax.plot(x, x+1, color="blue", linewidth=0.25) ax.plot(x, x+2, color="blue", linewidth=0.50) ax.plot(x, x+3, color="blue", linewidth=1.00) ax.plot(x, x+4, color="blue", linewidth=2.00) # possible linestype options ‘-‘, ‘–’, ‘-.’, ‘:’, ‘steps’ ax.plot(x, x+5, color="red", lw=2, linestyle='-') ax.plot(x, x+6, color="red", lw=2, ls='-.') ax.plot(x, x+7, color="red", lw=2, ls=':') # custom dash line, = ax.plot(x, x+8, color="black", lw=1.50) line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ... # possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4', ... ax.plot(x, x+ 9, color="green", lw=2, ls='*', marker='+') ax.plot(x, x+10, color="green", lw=2, ls='*', marker='o') ax.plot(x, x+11, color="green", lw=2, ls='*', marker='s') ax.plot(x, x+12, color="green", lw=2, ls='*', marker='1') # marker size and color ax.plot(x, x+13, color="purple", lw=1, ls='-', marker='o', markersize=2) ax.plot(x, x+14, color="purple", lw=1, ls='-', marker='o', markersize=4) ax.plot(x, x+15, color="purple", lw=1, ls='-', marker='o', markersize=8, markerfacecolor="red") ax.plot(x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8, markerfacecolor="yellow", markeredgewidth=2, markeredgecolor="blue") fig
控制座標軸的樣式
座標軸樣式也是一般須要自定義的地方,像是標號或是標籤的位置或是字體的大小等。
圖的範圍
咱們想作的第一件事也許是設置座標軸的範圍,可使用 set_ylim 或是 set_xlim 方法或者 axis(‘tight’) 自動將座標軸調整的緊湊 The first thing we might want to configure is the ranges of the axes. We can do this using the set_ylim and set_xlim methods in the axis object, or axis(‘tight’) for automatrically getting 「tightly fitted」 axes ranges:
fig, axes = plt.subplots(1, 3, figsize=(12, 4)) axes[0].plot(x, x**2, x, x**3) axes[0].set_title("default axes ranges") axes[1].plot(x, x**2, x, x**3) axes[1].axis('tight') axes[1].set_title("tight axes") axes[2].plot(x, x**2, x, x**3) axes[2].set_ylim([0, 60]) axes[2].set_xlim([2, 5]) axes[2].set_title("custom axes range"); fig
對數刻度
也能夠將軸的刻度設置成對數刻度,調用 set_xscale 與 set_yscale 設置刻度,參數選擇 「log」 :
fig, axes = plt.subplots(1, 2, figsize=(10,4)) axes[0].plot(x, x**2, x, exp(x)) axes[0].set_title("Normal scale") axes[1].plot(x, x**2, x, exp(x)) axes[1].set_yscale("log") axes[1].set_title("Logarithmic scale (y)"); fig
自定義標號位置與符號
set_xticks 與 set_yticks 方法能夠顯示地設置標號的位置, set_xticklabels 與 set_yticklabels 爲每個標號設置符號:
fig, ax = plt.subplots(figsize=(10, 4)) ax.plot(x, x**2, x, x**3, lw=2) ax.set_xticks([1, 2, 3, 4, 5]) ax.set_xticklabels([r'$\alpha$', r'$\beta$', r'$\gamma$', r'$\delta$', r'$\epsilon$'], fontsize=18) yticks = [0, 50, 100, 150] ax.set_yticks(yticks) ax.set_yticklabels(["$%.1f$" % y for y in yticks], fontsize=18); # use LaTeX formatted labels fig => [<matplotlib.text.Text at 0x5d75c90>, <matplotlib.text.Text at 0x585fe50>, <matplotlib.text.Text at 0x575c090>, <matplotlib.text.Text at 0x599e610>]
科學計數法
若是軸上涉及很是大的數,最好使用科學計數法:
fig, ax = plt.subplots(1, 1) ax.plot(x, x**2, x, exp(x)) ax.set_title("scientific notation") ax.set_yticks([0, 50, 100, 150]) from matplotlib import ticker formatter = ticker.ScalarFormatter(useMathText=True) formatter.set_scientific(True) formatter.set_powerlimits((-1,1)) ax.yaxis.set_major_formatter(formatter) fig
軸上數與標籤的間距
# distance between x and y axis and the numbers on the axes rcParams['xtick.major.pad'] = 5 rcParams['ytick.major.pad'] = 5 fig, ax = plt.subplots(1, 1) ax.plot(x, x**2, x, exp(x)) ax.set_yticks([0, 50, 100, 150]) ax.set_title("label and axis spacing") # padding between axis label and axis numbers ax.xaxis.labelpad = 5 ax.yaxis.labelpad = 5 ax.set_xlabel("x") ax.set_ylabel("y"); fig
調整座標軸的位置:
fig, ax = plt.subplots(1, 1) ax.plot(x, x**2, x, exp(x)) ax.set_yticks([0, 50, 100, 150]) ax.set_title("title") ax.set_xlabel("x") ax.set_ylabel("y") fig.subplots_adjust(left=0.15, right=.9, bottom=0.1, top=0.9); fig
座標軸網格
grid 方法能夠打開關閉網格線,也能夠自定義網格的樣式:
fig, axes = plt.subplots(1, 2, figsize=(10,3)) # default grid appearance axes[0].plot(x, x**2, x, x**3, lw=2) axes[0].grid(True) # custom grid appearance axes[1].plot(x, x**2, x, x**3, lw=2) axes[1].grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5) fig
軸
咱們也能夠改變軸的屬性:
fig, ax = plt.subplots(figsize=(6,2)) ax.spines['bottom'].set_color('blue') ax.spines['top'].set_color('blue') ax.spines['left'].set_color('red') ax.spines['left'].set_linewidth(2) # turn off axis spine to the right ax.spines['right'].set_color("none") ax.yaxis.tick_left() # only ticks on the left side fig
雙座標軸
twinx 與 twiny 函數能設置雙座標軸:
fig, ax1 = plt.subplots()
ax1.plot(x, x**2, lw=2, color="blue") ax1.set_ylabel(r"area $(m^2)$", fontsize=18, color="blue") for label in ax1.get_yticklabels(): label.set_color("blue") ax2 = ax1.twinx() ax2.plot(x, x**3, lw=2, color="red") ax2.set_ylabel(r"volume $(m^3)$", fontsize=18, color="red") for label in ax2.get_yticklabels(): label.set_color("red") fig
設置座標原點在(0,0)點
fig, ax = plt.subplots()
ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data',0)) # set position of x spine to x=0 ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data',0)) # set position of y spine to y=0 xx = np.linspace(-0.75, 1., 100) ax.plot(xx, xx**3); fig
包括通常的 plot 方法, 還有不少其餘函數可以生成不一樣類型的圖表,詳情請見 http://matplotlib.org/gallery.html 這裏列出其中幾種比較常見的函數方法。
n = array([0,1,2,3,4,5]) fig, axes = plt.subplots(1, 4, figsize=(12,3)) axes[0].scatter(xx, xx + 0.25*randn(len(xx))) axes[0].set_title("scatter") axes[1].step(n, n**2, lw=2) axes[1].set_title("step") axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5) axes[2].set_title("bar") axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5); axes[3].set_title("fill_between"); fig
# polar plot using add_axes and polar projection fig = plt.figure() ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True) t = linspace(0, 2 * pi, 100) ax.plot(t, t, color='blue', lw=3);
# A histogram n = np.random.randn(100000) fig, axes = plt.subplots(1, 2, figsize=(12,4)) axes[0].hist(n) axes[0].set_title("Default histogram") axes[0].set_xlim((min(n), max(n))) axes[1].hist(n, cumulative=True, bins=50) axes[1].set_title("Cumulative detailed histogram") axes[1].set_xlim((min(n), max(n))); fig
hist的參數含義
x : (n,) array or sequence of (n,) arrays
這個參數是指定每一個bin(箱子)分佈的數據,對應x軸
bins : integer or array_like, optional
這個參數指定bin(箱子)的個數,也就是總共有幾條條狀圖
normed : boolean, optional
If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e.,n/(len(x)`dbin)
這個參數指定密度,也就是每一個條狀圖的佔比例比,默認爲1
color : color or array_like of colors or None, optional
這個指定條狀圖的顏色
參見: hist的使用
餅狀圖
import matplotlib.pyplot as plt labels='frogs','hogs','dogs','logs' sizes=15,20,45,10 colors='yellowgreen','gold','lightskyblue','lightcoral' explode=0,0.1,0,0 plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=50) plt.axis('equal') plt.show()
文本註釋
text 函數能夠作文本註釋,且支持 LaTeX 格式:
fig, ax = plt.subplots()
ax.plot(xx, xx**2, xx, xx**3) ax.text(0.15, 0.2, r"$y=x^2$", fontsize=20, color="blue") ax.text(0.65, 0.1, r"$y=x^3$", fontsize=20, color="green"); fig
帶有多子圖與插圖的圖
fig.add_axes 在圖中加入新座標軸
subplots, subplot2grid,gridspec等 子圖佈局管理器
subplots
fig, ax = plt.subplots(2, 3)
fig.tight_layout()
fig
subplot2grid
fig = plt.figure()
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1,2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2,0))
ax5 = plt.subplot2grid((3,3), (2,1))
fig.tight_layout()
fig
顏色映射圖與輪廓圖
顏色映射圖與輪廓圖適合繪製兩個變量的函數。
matplotlib也能夠畫3D圖,這裏暫且略過。
轉載於:http://whuhan2013.github.io/blog/2016/09/16/python-matplotlib-learn/