matplotlib學(xué)習(xí)記錄總結(jié)(2)

特大聲明:本文復(fù)制于實驗樓網(wǎng)站

Matplotlib 是一個優(yōu)秀的 2D&3D 圖形庫, 主要功能是生成科學(xué)用圖,它的優(yōu)點包括:

  • 上手容易
  • 支持 LaTeX 格式的標簽與文本
  • 能夠很好地控制圖中的每一樣元素,包括圖的大小與 DPI
  • 高質(zhì)量保存,支持多種格式, 包括 PNG, PDF, SVG, EPS, 與 PGF。
  • 可交互的圖形界面,支持生成無頭部信息的圖表文件

1.3 實驗?zāi)夸?/h3>
  • 2.1 類MATLAB API
    • MATLAB API 繪圖示例
  • 2.2 matplotlib 面向?qū)ο?API
    • 2.2.1 圖表尺寸,長寬比 與 DPI
    • 2.2.2 保存圖表
      • 有哪些格式?哪種格式能獲得最佳質(zhì)量?
    • 2.2.3 圖例,軸標 與 標題
    • 2.2.4 格式化文本,LaTeX,字體大小,字體類型
    • 2.2.5 設(shè)置顏色,線寬 與 線型
      • 顏色
      • 線與描點風(fēng)格
    • 2.2.6 控制坐標軸的樣式
      • 圖的范圍
      • 對數(shù)刻度
    • 2.2.7 自定義標號位置與符號
      • 科學(xué)計數(shù)法
    • 2.2.8軸上數(shù)與標簽的間距
      • 調(diào)整坐標軸的位置:
    • 2.2.9 坐標軸網(wǎng)格
    • 2.2.10 軸
    • 2.2.11 雙坐標軸
    • 2.2.12 設(shè)置坐標原點在(0,0)點
    • 2.2.13 其他 2D 圖表風(fēng)格
    • 2.2.14 文本注釋
    • 2.2.15 帶有多子圖與插圖的圖
      • subplots
      • subplot2grid
      • gridspec
      • add_axes
    • 2.2.16 顏色映射圖與輪廓圖
      • pcolor
      • imshow
      • contour

(不要被這個目錄嚇怕了,其實內(nèi)容不太多。)

二、實驗內(nèi)容

2.1 類MATLAB API

最簡單的入門是從類 MATLAB API 開始,它被設(shè)計成兼容 MATLAB 繪圖函數(shù)。

讓我們加載它:

from pylab import *

使用 qt 作為圖形后端:

%matplotlib qt

MATLAB API 繪圖示例

類MATLAB API 繪圖的簡單例子:

from numpy import *
x = linspace(0, 5, 10)
y = x ** 2

figure()
plot(x, y, 'r')
xlabel('x')
ylabel('y')
title('title')
show()
此處輸入圖片的描述

創(chuàng)建子圖,選擇繪圖用的顏色與描點符號:

subplot(1,2,1)
plot(x, y, 'r--')
subplot(1,2,2)
plot(y, x, 'g*-');
此處輸入圖片的描述

此類 API 的好處是可以節(jié)省你的代碼量,但是我們并不鼓勵使用它處理復(fù)雜的圖表。處理復(fù)雜圖表時, matplotlib 面向?qū)ο?API 是一個更好的選擇。

2.2 matplotlib 面向?qū)ο?API

首先讓我們加載它:

import matplotlib.pyplot as plt

使用面向?qū)ο驛PI的方法和之前例子里的看起來很類似,不同的是,我們并不創(chuàng)建一個全局實例,而是將新建實例的引用保存在 fig 變量中,如果我們想在圖中新建一個坐標軸實例,只需要
調(diào)用 fig 實例的 add_axes 方法:

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')

fig
此處輸入圖片的描述

盡管會寫更多的代碼,好處在于我們對于圖表的繪制有了完全的控制權(quán),可以很容易地多加一個坐標軸到圖中:

fig = plt.figure()

axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes

# main figure
axes1.plot(x, y, 'r')
axes1.set_xlabel('x')
axes1.set_ylabel('y')
axes1.set_title('title')

# insert
axes2.plot(y, x, 'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('insert title');

fig
此處輸入圖片的描述

如果我們不在意坐標軸在圖中的排放位置?,那么就可以使用matplotlib的布局管理器了,我最喜歡的是subplots,使用方式如下:

fig, axes = plt.subplots()

axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');

fig
此處輸入圖片的描述
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
此處輸入圖片的描述

很簡單吧,但是標簽重疊就不好看了。可以使用 fig.tight_layout 解決這個問題,它會自動調(diào)整標簽的位置:

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()
fig
此處輸入圖片的描述

2.2.1 圖表尺寸,長寬比 與 DPI

在創(chuàng)建 Figure 對象的時候,使用figsizedpi 參數(shù)能夠設(shè)置圖表尺寸與DPI,
創(chuàng)建一個800*400像素,每英寸100像素的圖就可以這么做:

fig = plt.figure(figsize=(8,4), dpi=100)


<matplotlib.figure.Figure at 0x4cbd390>

同樣的參數(shù)也可以用在布局管理器上:

fig, axes = plt.subplots(figsize=(12,3))

axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');
此處輸入圖片的描述

2.2.2 保存圖表

可以使用 savefig 保存圖表

fig.savefig("filename.png")

這里我們也可以有選擇地指定DPI,并且選擇不同的輸出格式:

fig.savefig("filename.png", dpi=200)

有哪些格式?哪種格式能獲得最佳質(zhì)量?

Matplotlib 可以生成多種格式的高質(zhì)量圖像,包括PNG,JPG,EPS,SVG,PGF 和 PDF。如果是科學(xué)論文的話,我建議盡量使用pdf格式。 (pdflatex 編譯的 LaTeX 文檔使用 includegraphics 命令就能包含 PDF 文件)。 一些情況下,PGF也是一個很好的選擇。

2.2.3 圖例,軸標 與 標題

現(xiàn)在我們已經(jīng)介紹了如何創(chuàng)建圖表畫布以及如何添加新的坐標軸實例,讓我們看一看如何加上標題,軸標和圖例

標題

每一個坐標軸實例都可以加上一個標題,只需調(diào)用坐標軸實例的 set_title 方法:

ax.set_title("title");

軸標

類似的, set_xlabelset_ylabel 可以設(shè)置坐標軸的x軸與y軸的標簽。

ax.set_xlabel("x")
ax.set_ylabel("y");

圖例

有兩種方法在圖中加入圖例。一種是調(diào)用坐標軸對象的 legend 方法,傳入與之前定義的幾條曲線相對應(yīng)地圖例文字的 列表/元組:

ax.legend(["curve1", "curve2", "curve3"]);

不過這種方式容易出錯,比如增加了新的曲線或者移除了某條曲線。更好的方式是在調(diào)用 plot方法時使用 label="label text" 參數(shù),再調(diào)用 legend 方法加入圖例:

ax.plot(x, x**2, label="curve1")
ax.plot(x, x**3, label="curve2")
ax.legend();

legend 還有一個可選參數(shù) 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>

下面這個例子同時包含了標題,軸標,與圖例的用法:

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');

fig
此處輸入圖片的描述

2.2.4 格式化文本,LaTeX,字體大小,字體類型

Matplotlib 對 LaTeX 提供了很好的支持。我們只需要將 LaTeX 表達式封裝在 $ 符號內(nèi),就可以在圖的任何文本中顯示了,比如 "$y=x^3$" 。

不過這里我們會遇到一些小問題,在 LaTeX 中我們常常會用到反斜杠,比如 \alpha 來產(chǎn)生符號 $\alpha$ 。但反斜杠在 python 字符串中是有特殊含義的。為了不出錯,我們需要使用原始文本,只需要在字符串的前面加個r就行了,像是 r"\alpha" 或者 r'\alpha'

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');

fig
此處輸入圖片的描述

我們可以更改全局字體大小或者類型:

# Update the matplotlib configuration parameters:
from matplotlib import rcParams
rcParams.update({'font.size': 18, 'font.family': 'serif'})


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$')
ax.set_ylabel(r'$y$')
ax.set_title('title');

fig
此處輸入圖片的描述

STIX 字體是一種好選擇:

# Update the matplotlib configuration parameters:
matplotlib.rcParams.update({'font.size': 18, 'font.family': 'STIXGeneral', 'mathtext.fontset': 'stix'})


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$')
ax.set_ylabel(r'$y$')
ax.set_title('title');

fig
此處輸入圖片的描述

我們也可以將圖中的文本全用 Latex 渲染:

matplotlib.rcParams.update({'font.size': 18, 'text.usetex': True})


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$')
ax.set_ylabel(r'$y$')
ax.set_title('title');

fig
此處輸入圖片的描述
# 重置
matplotlib.rcParams.update({'font.size': 12, 'font.family': 'sans', 'text.usetex': False})

2.2.5 設(shè)置顏色,線寬 與 線型

顏色

有了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參數(shù)決定了顏色的透明度:

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>]
此處輸入圖片的描述

線與描點風(fēng)格

linewidth 或是 lw 參數(shù)改變線寬。
linestyle 或是 ls 參數(shù)改變線的風(fēng)格。

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
此處輸入圖片的描述

2.2.6 控制坐標軸的樣式

坐標軸樣式也是通常需要自定義的地方,像是標號或是標簽的位置或是字體的大小等。

圖的范圍

我們想做的第一件事也許是設(shè)置坐標軸的范圍,可以使用 set_ylim 或是 set_xlim 方法或者 axis('tight') 自動將坐標軸調(diào)整的緊湊
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
此處輸入圖片的描述

對數(shù)刻度

也可以將軸的刻度設(shè)置成對數(shù)刻度,調(diào)用 set_xscaleset_yscale 設(shè)置刻度,參數(shù)選擇 "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
此處輸入圖片的描述

2.2.7 自定義標號位置與符號

set_xticksset_yticks 方法可以顯示地設(shè)置標號的位置,
set_xticklabelsset_yticklabels 為每一個標號設(shè)置符號:

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>]
此處輸入圖片的描述

還有許多方法可以控制主次標號,參考 http://matplotlib.org/api/ticker_api.html

科學(xué)計數(shù)法

如果軸上涉及非常大的數(shù),最好使用科學(xué)計數(shù)法:

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
此處輸入圖片的描述

2.2.8軸上數(shù)與標簽的間距

# 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
此處輸入圖片的描述
# restore defaults
rcParams['xtick.major.pad'] = 3
rcParams['ytick.major.pad'] = 3

調(diào)整坐標軸的位置:

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
此處輸入圖片的描述

2.2.9 坐標軸網(wǎng)格

grid 方法可以打開關(guān)閉網(wǎng)格線,也可以自定義網(wǎng)格的樣式:

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
此處輸入圖片的描述

2.2.10 軸

我們也可以改變軸的屬性:

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
此處輸入圖片的描述

2.2.11 雙坐標軸

twinxtwiny 函數(shù)能設(shè)置雙坐標軸:

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
此處輸入圖片的描述

2.2.12 設(shè)置坐標原點在(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
此處輸入圖片的描述

2.2.13 其他 2D 圖表風(fēng)格

包括一般的 plot 方法, 還有很多其他函數(shù)能夠生成不同類型的圖表,詳情請見 http://matplotlib.org/gallery.html 這里列出其中幾種比較常見的函數(shù)方法。

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
此處輸入圖片的描述

2.2.14 文本注釋

text 函數(shù)可以做文本注釋,且支持 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
此處輸入圖片的描述

2.2.15 帶有多子圖與插圖的圖

fig.add_axes 在圖中加入新坐標軸

subplots, subplot2gridgridspec等 子圖布局管理器

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
此處輸入圖片的描述

gridspec

import matplotlib.gridspec as gridspec


fig = plt.figure()

gs = gridspec.GridSpec(2, 3, height_ratios=[2,1], width_ratios=[1,2,1])
for g in gs:
    ax = fig.add_subplot(g)
    
fig.tight_layout()

fig
此處輸入圖片的描述

add_axes

fig, ax = plt.subplots()

ax.plot(xx, xx**2, xx, xx**3)
fig.tight_layout()

# inset
inset_ax = fig.add_axes([0.2, 0.55, 0.35, 0.35]) # X, Y, width, height

inset_ax.plot(xx, xx**2, xx, xx**3)
inset_ax.set_title('zoom near origin')

# set axis range
inset_ax.set_xlim(-.2, .2)
inset_ax.set_ylim(-.005, .01)

# set axis tick locations
inset_ax.set_yticks([0, 0.005, 0.01])
inset_ax.set_xticks([-0.1,0,.1]);

fig
此處輸入圖片的描述

2.2.16 顏色映射圖與輪廓圖

顏色映射圖與輪廓圖適合繪制兩個變量的函數(shù)。

有許多預(yù)定義的顏色映射圖,參考:http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps

alpha = 0.7
phi_ext = 2 * pi * 0.5

def flux_qubit_potential(phi_m, phi_p):
    return 2 + alpha - 2 * cos(phi_p)*cos(phi_m) - alpha * cos(phi_ext - 2*phi_p)


phi_m = linspace(0, 2*pi, 100)
phi_p = linspace(0, 2*pi, 100)
X,Y = meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T

pcolor

fig, ax = plt.subplots()

p = ax.pcolor(X/(2*pi), Y/(2*pi), Z, cmap=plt.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max())
cb = fig.colorbar(p, ax=ax)

fig
此處輸入圖片的描述

imshow

fig, ax = plt.subplots()

im = ax.imshow(Z, cmap=cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1])
im.set_interpolation('bilinear')

cb = fig.colorbar(im, ax=ax)

fig
此處輸入圖片的描述

contour

fig, ax = plt.subplots()

cnt = ax.contour(Z, cmap=cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1])

fig
此處輸入圖片的描述
  • 2.3 3D 圖
    • 2.3.1 繪制曲面
    • 2.3.2 繪制線框
    • 2.3.3 繪制投影輪廓
    • 2.3.4 改變視圖角度
  • 2.4 動畫
  • 2.5 后端
    • 2.5.1 使用 svg 后端生成 svg 圖片
    • 2.5.2 可交互后端

2.3 3D 圖

在matploylib中創(chuàng)建3d圖,首先要做的是創(chuàng)建 Axes3D

from mpl_toolkits.mplot3d.axes3d import Axes3D

2.3.1 繪制曲面

fig = plt.figure(figsize=(14,6))

# `ax` is a 3D-aware axis instance because of the projection='3d' keyword argument to add_subplot
ax = fig.add_subplot(1, 2, 1, projection='3d')

p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)

# surface_plot with color grading and color bar
ax = fig.add_subplot(1, 2, 2, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
cb = fig.colorbar(p, shrink=0.5)
此處輸入圖片的描述

2.3.2 繪制線框

fig = plt.figure(figsize=(8,6))

ax = fig.add_subplot(1, 1, 1, projection='3d')

p = ax.plot_wireframe(X, Y, Z, rstride=4, cstride=4)
此處輸入圖片的描述

2.3.3 繪制投影輪廓

fig = plt.figure(figsize=(8,6))

ax = fig.add_subplot(1,1,1, projection='3d')

ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
cset = ax.contour(X, Y, Z, zdir='z', offset=-pi, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-pi, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=3*pi, cmap=cm.coolwarm)

ax.set_xlim3d(-pi, 2*pi);
ax.set_ylim3d(0, 3*pi);
ax.set_zlim3d(-pi, 2*pi);
此處輸入圖片的描述

2.3.4 改變視圖角度

view_init 可以改變視圖角度,讀取兩個參數(shù): elevationazimuth 角度

fig = plt.figure(figsize=(12,6))

ax = fig.add_subplot(1,2,1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
ax.view_init(30, 45)

ax = fig.add_subplot(1,2,2, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
ax.view_init(70, 30)

fig.tight_layout()
此處輸入圖片的描述

2.4 動畫

FuncAnimation 函數(shù)能根據(jù)一系列圖生成動畫,它有以下參數(shù):

fig:圖的畫布

func:更新圖的函數(shù)

init_func:初始化圖的函數(shù)

frame:圖的數(shù)量

blit:告訴動畫函數(shù)只更新改動的部分:

def init():
    # setup figure

def update(frame_counter):
    # update figure for new frame

anim = animation.FuncAnimation(fig, update, init_func=init, frames=200, blit=True)

anim.save('animation.mp4', fps=30) # fps = frames per second

為了使用動畫特性,首先加載模塊 matplotlib.animation

from matplotlib import animation


# solve the ode problem of the double compound pendulum again

from scipy.integrate import odeint

g = 9.82; L = 0.5; m = 0.1

def dx(x, t):
    x1, x2, x3, x4 = x[0], x[1], x[2], x[3]
    
    dx1 = 6.0/(m*L**2) * (2 * x3 - 3 * cos(x1-x2) * x4)/(16 - 9 * cos(x1-x2)**2)
    dx2 = 6.0/(m*L**2) * (8 * x4 - 3 * cos(x1-x2) * x3)/(16 - 9 * cos(x1-x2)**2)
    dx3 = -0.5 * m * L**2 * ( dx1 * dx2 * sin(x1-x2) + 3 * (g/L) * sin(x1))
    dx4 = -0.5 * m * L**2 * (-dx1 * dx2 * sin(x1-x2) + (g/L) * sin(x2))
    return [dx1, dx2, dx3, dx4]

x0 = [pi/2, pi/2, 0, 0]  # initial state
t = linspace(0, 10, 250) # time coordinates
x = odeint(dx, x0, t)    # solve the ODE problem

生成雙擺的運動動畫:

fig, ax = plt.subplots(figsize=(5,5))

ax.set_ylim([-1.5, 0.5])
ax.set_xlim([1, -1])

pendulum1, = ax.plot([], [], color="red", lw=2)
pendulum2, = ax.plot([], [], color="blue", lw=2)

def init():
    pendulum1.set_data([], [])
    pendulum2.set_data([], [])

def update(n): 
    # n = frame counter
    # calculate the positions of the pendulums
    x1 = + L * sin(x[n, 0])
    y1 = - L * cos(x[n, 0])
    x2 = x1 + L * sin(x[n, 1])
    y2 = y1 - L * cos(x[n, 1])
    
    # update the line data
    pendulum1.set_data([0 ,x1], [0 ,y1])
    pendulum2.set_data([x1,x2], [y1,y2])

anim = animation.FuncAnimation(fig, update, init_func=init, frames=len(t), blit=True)

# anim.save can be called in a few different ways, some which might or might not work
# on different platforms and with different versions of matplotlib and video encoders
#anim.save('animation.mp4', fps=20, extra_args=['-vcodec', 'libx264'], writer=animation.FFMpegWriter())
#anim.save('animation.mp4', fps=20, extra_args=['-vcodec', 'libx264'])
#anim.save('animation.mp4', fps=20, writer="ffmpeg", codec="libx264")
anim.save('animation.mp4', fps=20, writer="avconv", codec="libx264")

plt.close(fig)

為了生成動畫,首先需要安裝 libav-tools

$ sudo apt-get install libav-tools

在terminal播放動畫吧:

$ avplay animation.mp4

2.5 后端

Matplotlib 有很多用來渲染圖片的后端:

print(matplotlib.rcsetup.all_backends)

['GTK', 'GTKAgg', 'GTKCairo', 'MacOSX', 'Qt4Agg', 'TkAgg', 'WX', 'WXAgg', 'CocoaAgg', 'GTK3Cairo', 'GTK3Agg', 'WebAgg', 'agg', 'cairo', 'emf', 'gdk', 'pdf', 'pgf', 'ps', 'svg', 'template']

默認后端是 agg,適合生成光柵圖,比如 PNG。

一般情況都不用切換后端,但如果希望生成高清矢量圖,可以切換成 PDF 或者 GTKCairo。

2.5.1 使用 svg 后端生成 svg 圖片

#
# RESTART THE NOTEBOOK: the matplotlib backend can only be selected before pylab is imported!
# (e.g. Kernel > Restart)
# 
import matplotlib
matplotlib.use('svg')
import matplotlib.pylab as plt
import numpy
from IPython.display import Image, SVG


#
# Now we are using the svg backend to produce SVG vector graphics
#
fig, ax = plt.subplots()
t = numpy.linspace(0, 10, 100)
ax.plot(t, numpy.cos(t)*numpy.sin(t))
plt.savefig("test.svg")


#
# Show the produced SVG file. 
#
SVG(filename="test.svg")
此處輸入圖片的描述

2.5.2 可交互后端

#
# RESTART THE NOTEBOOK: the matplotlib backend can only be selected before pylab is imported!
# (e.g. Kernel > Restart)
# 
import matplotlib
matplotlib.use('Qt4Agg') # or for example MacOSX
import matplotlib.pylab as plt
import numpy


# Now, open an interactive plot window with the Qt4Agg backend
fig, ax = plt.subplots()
t = numpy.linspace(0, 10, 100)
ax.plot(t, numpy.cos(t)*numpy.sin(t))
plt.show()

當我們使用可交互后端時,需調(diào)用 plt.show() 才能使圖片顯示出來。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Matplotlib 入門教程 來源:Introduction to Matplotlib and basic l...
    布客飛龍閱讀 32,276評論 5 162
  • 前言: Python初學(xué)者,希望各位大佬看了文章后能指出錯誤或者給些建議! 如有雷同,純屬巧合! = =! 環(huán)境 ...
    學(xué)編程的Dreamer閱讀 2,027評論 0 4
  • 圖例指南 原文:Legend guide 譯者:飛龍 協(xié)議:CC BY-NC-SA 4.0 此圖例指南是legen...
    布客飛龍閱讀 2,795評論 1 5
  • 其實是有點喜歡寫些東西的,好像是從剛開始學(xué)寫作文的時候開始,我記得我寫的第一篇作文,被老師當成范文在課堂上朗...
    有好多好閱讀 226評論 0 0
  • 舊朋友 昨天在微信里加了一個舊朋友。也許你會好奇,為什么不是老朋友而是舊朋友呢?在我的眼里,舊朋友是那些久久沒有聯(lián)...
    咚_閱讀 482評論 0 0

友情鏈接更多精彩內(nèi)容