之前斷斷續(xù)續(xù)的看了不少關(guān)于 Matplotlib 的教程嗅绰,也做了一些練習(xí),但時常被不同演示中繁雜且各異的命令所迷惑败徊。今天剛好看到了 Chris Moffitt 的這篇文章 Effective Matplotlib尿这,覺得有必要結(jié)合官網(wǎng)從更高的視角了解 Matplotlib 的工作機制,在此更新這個筆記蝙斜。
首先,在 Matplotlib 中 figure 結(jié)合了 canvas 和 axes 構(gòu)成了我們看到的最終的圖像本身白翻,其中一個 figure 中可以包含一個或多個 axes乍炉,而每一個 axes 則是一系列 artists 如坐標(biāo)軸 axis绢片,標(biāo)簽 label滤馍,標(biāo)題 title,圖例 legend 的集合底循。在程序中 figure 常用 fig 變量來指代巢株,而 axes 常用 ax 變量來指代,鑒于各個對象間的層級結(jié)構(gòu)關(guān)系熙涤,在使用中獲取了 fig 和 ax 的控制權(quán)就可以對其中的元素進行修改阁苞。
其次,Matplotlib 的首選輸入是列表和 Numpy 中的數(shù)組祠挫,任何其他類型的輸入包括 Pandas 的數(shù)據(jù)類型那槽,如 np.matrix 等都應(yīng)該轉(zhuǎn)化成數(shù)組,否則 Matplotlib 會內(nèi)部自動轉(zhuǎn)化等舔,但由于轉(zhuǎn)換的形式不一定是我們想要的骚灸,因此最終生成的圖像可能不是預(yù)期的樣式。
約定引用方式:
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
# this very last line ask the backend to generate higher resolution figures
應(yīng)用實例
折線圖
plt.plot()
的輸入為待可視的橫慌植、縱坐標(biāo)值甚牲,并可以指定線型义郑,寬度,顏色等:
input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
plt.plot(input_values, squares, linewidth=3)
圖形的標(biāo)題丈钙,橫縱坐標(biāo)的標(biāo)簽和都可以分別通過 plt.title()
, plt.xlabel()
, plt.ylabel()
指定:
plt.title("Square Numbers", fontsize=20)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
plt.tick_params(axis='both', labelsize=14)
plt.show()
plt.plot()
第一次使用時會自動創(chuàng)建相應(yīng)的 figure 和 axes 來完成圖表的繪制非驮,后續(xù)添加的 plt.plot()
命令會在之前的 axes 上繼續(xù)增加新的 artists 內(nèi)容:
# code adopted from matplotlib website
x = np.linspace(0, 2, 100)
plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
# plt.axis() takes a list of [xmin, xmax, ymin, ymax]
plt.axis([1, 2, 1, 8])
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()
plt.show()
在一個 figure 上繪制多個 axes 需要采用 plt.subplot()
命令:
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
# subplot() command specifies numrows, numcols, fignum
# where fignum ranges from 1 to numrows*numcols
plt.subplot(211) # the same as plt.subplot(2, 1, 1)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
在一個 figure 中繪制多個 axes 時有兩個函數(shù):plt.subplot()
和 plt.subplots()
,后者返回 figure 和 一個或多個 axes 雏赦,此后對于圖像中元素的操作都是基于 ax.method()
而無需采用采用 plt.method()
的形式劫笙,其使用方法為:
# Get the figure and the axes
fig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(10,4))
# Build the first plot
top_10.plot(kind='barh', x='Name', y='Sales', ax=ax0)
ax0.set(title='Revenue', xlabel='Total revenue', ylabel='Customers')
formatter = FuncFormatter(currency)
ax0.xaxis.set_major_formatter(formatter)
# Add average line to the first plot
revenue_average = top_10['Sales'].mean()
ax0.axvline(x=revenue_average, color='b', label='Average', linestyle='--', linewidth=1)
# Build the second plot
top_10.plot(kind='barh', x='Name', y='Purchases', ax=ax1)
ax1.set(title='Units', xlabel='Total units', ylabel='')
# Add average line to the second plot
purchases_average = top_10['Purchases'].mean()
ax1.axvline(x=purchases_average, color='b', label='Average', linestyle='--', linewidth=1)
# Title the figure
fig.suptitle('2014 Sales Analysis', fontsize=14, fontweight='bold')
# Hide the plot legends
ax0.legend().set_visible(False)
ax1.legend().set_visible(False)
注意:上面這一段代碼和圖片來自于Effective Matplotlib,版權(quán)歸屬于 Chris Moffitt 本人喉誊。
如果在繪制多個 axes 時想指定不同 axes 的位置邀摆,則需要顯式的使用 axes([left, bottom, width, height]) 來指定位置,注意參數(shù)提供的是相對于坐標(biāo)軸的比例值伍茄,而非絕對值:
dt = 0.001
t = np.arange(0.0, 10.0, dt)
r = np.exp(-t[:1000]/0.05) # impulse response
x = np.random.randn(len(t))
s = np.convolve(x, r)[:len(x)]*dt # colored noise
# the main axes is subplot(111) by default
plt.plot(t, s)
plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)])
plt.xlabel('time (s)')
plt.ylabel('current (nA)')
plt.title('Gaussian colored noise')
# this is an inset axes over the main axes
a = plt.axes([.65, .6, .2, .2], facecolor='y')
n, bins, patches = plt.hist(s, 400, normed=1)
plt.title('Probability')
plt.xticks([])
plt.yticks([])
# this is another inset axes over the main axes
a = plt.axes([0.2, 0.6, .2, .2], facecolor='y')
plt.plot(t[:len(r)], r)
plt.title('Impulse response')
plt.xlim(0, 0.2)
plt.xticks([])
plt.yticks([])
plt.show()
散點圖
上述手動輸入的 list 作為數(shù)據(jù)源僅僅是為了便于展示栋盹,在日常的使用中,更多的是根據(jù)已有的數(shù)據(jù)生成圖形敷矫。在散點圖中可以通過參數(shù) c 來指定顏色例获,其輸入的值可以是 str, (R, G, B), 也可以是逐點改變的數(shù)值來顯示漸變;s 指定單個圓點的大胁苷獭柏锄;默認(rèn)情況下在圓點的外周會有一個黑色的邊框,可以通過edgecolor='none'
來取消邊框或通過其他值來改變顏色滔以。
x = list(range(1, 1001))
y = [e*e for e in x]
# 第一行顏色指定為紅色蝗锥,第二行顏色為(R, G, B)值
# 第三行通過引用 cmp( color map)關(guān)鍵詞引入漸變
#plt.scatter(x, y, c='red', edgecolor='none', s=20)
#plt.scatter(x, y, c=(0, 0, 0.8), edgecolor='none', s=5)
plt.scatter(x, y, c=y, cmap=plt.cm.Blues, edgecolor='none', s=5)
# Set chart title and label axes
plt.title("Square Numbers", fontsize=20)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# Set size of tick labels
plt.tick_params(axis='both', which='major', labelsize=14)
# Set the range for each axis
plt.axis([0, 1100, 0, 1100000])
plt.show()
參考閱讀
Matplotlib website - The Matplotlib FAQ
Matplotlib website - pyplot tutorial
Chris Moffitt - Effective matplotlib