matplotlib神器
當(dāng)我們完善地處理好數(shù)據(jù)唬格,還需將其用于與他人的交流家破,僅遞上冰冷的數(shù)據(jù),很難產(chǎn)生良好的效果购岗。于是汰聋,為滿足將數(shù)據(jù)圖形化、令閱讀者一目了然的需求藕畔,matplotlib應(yīng)運(yùn)而生马僻。
1、一個(gè)簡(jiǎn)單的圖形
通過(guò)調(diào)用matplotlib第三方庫(kù)注服,我們敲入簡(jiǎn)單的幾行代碼韭邓,便可紛繁的數(shù)據(jù)繪制成圖。例如:
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
x = range(0,100,3)
y = [(a+1)*2 for a in x]
plt.plot(x,y)
plt.show()
2溶弟、設(shè)置內(nèi)容的層次
對(duì)于一個(gè)圖形女淑,我們要設(shè)置的內(nèi)容主要有以下幾個(gè)方面:
其中,Title為標(biāo)題辜御。Axis為坐標(biāo)軸鸭你,Label為坐標(biāo)軸標(biāo)注。Tick為刻度線擒权,Tick Label為刻度注釋袱巨。
當(dāng)我們要?jiǎng)?chuàng)建一個(gè)新圖形,可以輸入fig = plt.figure()
碳抄,得到一個(gè)沒(méi)有內(nèi)容的空?qǐng)D愉老。
3、如何擺放小圖
在一幅空?qǐng)D中剖效,我們可以根據(jù)需要嫉入,擺放一些小圖:
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 1, 2)
add_subplot(2, 2, 1)的意思是,在2X2的空間里璧尸,有四個(gè)擺圖的位置咒林,選定第1個(gè)位置。如果add_subplot(2, 1, 2)爷光,就是在2X1的寬圖中垫竞,選擇第二行的圖片。上面這串代碼整合起來(lái)的結(jié)果如下:
如果現(xiàn)在執(zhí)行plt.plot(np.random.randn(100).cumsum())
瞎颗,程序會(huì)在最后一個(gè)用過(guò)的subplot上畫(huà)圖件甥,如果之前沒(méi)有圖捌议,則程序會(huì)自動(dòng)創(chuàng)建一個(gè)圖,并隱藏創(chuàng)建figure和subplot的過(guò)程引有。下面試著輸入:
i=0
while i<200 :
plt.plot(np.random.randn(100).cumsum(), 'k--')
i += 1
畫(huà)圖200次后瓣颅,得到了正態(tài)分布二叉樹(shù)的圖形:
4、畫(huà)直方圖和散點(diǎn)圖
ax1.hist(np.random.randn(150), bins=30, color='g', alpha=0.5) # 直方圖
ax2.scatter(np.arange(50), np.arange(50) + 5 * np.random.randn(50)) # 散點(diǎn)圖
5譬正、用索引的方式管理小圖
除了用add_subplot(2, 2, 1)函數(shù)創(chuàng)建小圖宫补,還可以用plt.subplot()的方式創(chuàng)建,后者可以自動(dòng)返回一個(gè)包含小圖對(duì)象的NumPy數(shù)組曾我,可以作為用索引來(lái)管理小圖的工具粉怕。例如:
In[340]:
fig, axes = plt.subplots(3,2)
axes
Out[340]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000000001565C860>,
<matplotlib.axes._subplots.AxesSubplot object at 0x000000001582A5F8>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x0000000015A38080>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000000015885B38>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x0000000015BA0860>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000000015CA8438>]],
dtype=object)
In [342]: axes[0,1]
Out [342]: <matplotlib.axes._subplots.AxesSubplot at 0x1630c4e0>
除此之外,還可以用以下參數(shù)來(lái)管理subplot:
7抒巢、小圖間距的調(diào)整
小圖可以有寬的間距贫贝,也可以完全取消間距。調(diào)整間距可以提升繪圖的逼格蛉谜。
若要取消間距稚晚,可輸入:
fig, axes = plt.subplots(3,2,sharex=True, sharey=True)
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0)
得到:
6、線型型诚、顏色客燕、標(biāo)記點(diǎn)
在畫(huà)圖的代碼中,'k--'表示用黑色狰贯、虛線來(lái)繪制圖形也搓,這是快捷的做法。完整的語(yǔ)法是plt.plot(np.random.randn(100).cumsum(), color='k', linestyle=‘--’)
如果要在數(shù)據(jù)節(jié)點(diǎn)加黑圈涵紊,可以在參數(shù)中加入marker='o'
,或簡(jiǎn)寫(xiě)為go-- #(綠色虛線為'g--')
傍妒,不過(guò)需要注意,標(biāo)記類型和線型必須放在顏色后面摸柄。
另外拍顷,在數(shù)據(jù)節(jié)點(diǎn)之間,matplotlib默認(rèn)使用線性插值塘幅,可用參數(shù)drawstyle
來(lái)修改,例如drawstyle=‘steps-post’
fig = plt.figure()
plt.subplot(1,1,1)
data = np.random.randn(100).cumsum()
plt.plot(data, 'k--', label='Normal')
plt.plot(data, 'g-', drawstyle='steps-post', label='steps-post')
plt.legend(loc='best')
7尿贫、刻度电媳、標(biāo)簽、圖例
坐標(biāo)軸的刻度庆亡、標(biāo)簽匾乓,可用以下方式設(shè)置:
ticks = ax.set_xticks(np.linspace(0,100,5))
labels = ax.set_xticklabels(np.linspace(0,100,5),rotation=30, fontsize='large') # rotation表示標(biāo)簽旋轉(zhuǎn)30度
ax.set_xlabel(u'x軸標(biāo)簽')
#也可以用set()的方式得到同樣的效果:
# props = {
# 'title': 'hello',
# 'xlabel':u'xlabel'
# }
# ax.set(**props)
創(chuàng)建圖例的方法:
ax.plot(np.random.randn(1000).cumsum(), 'k', label='one')
ax.plot(np.random.randn(1000).cumsum(), 'k--', label='two')
ax.plot(np.random.randn(1000).cumsum(), 'k.', label='three')
plt.legend(loc='best') # 或用ax.legend() 來(lái)調(diào)用圖例
# 要從圖例中去除一個(gè)或多個(gè)元素,不傳入label或傳入label='nolegend'即可
運(yùn)行結(jié)果如下:
8又谋、在圖中添加注解
添加注解使用的函數(shù)主要用text()拼缝、arrow()娱局、annotate()。
test()可以在制定的坐標(biāo)位置(x,y)寫(xiě)入文本內(nèi)容:
fig = plt.figure()
fig.suptitle('use suptitle()', fontsize=14, fontweight='bold')
ax = fig.add_subplot(1,1,1)
fig.subplots_adjust(top=0.85)
ax.set_title('use set_title()')
ax.set_xlabel('use set_xlabel')
ax.set_ylabel('use set_ylabel')
ax.text(3, 8, 'use text() in data coords', style='italic',bbox={'facecolor':'gray', 'alpha':0.5, 'pad':5}) #pad是box的大小
ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=20)
ax.text(5, 2, u'what\'s up?')
ax.text(0.95, 0.01, 'colored text in axes coords',
verticalalignment='bottom', horizontalalignment='right',
transform=ax.transAxes,
color='green', fontsize=25)
ax.plot([2], [1], 'o') #加個(gè)節(jié)點(diǎn)標(biāo)識(shí)
ax.annotate('use annotate()', xy=(2, 1), xytext=(3, 4),
arrowprops=dict(facecolor='black', shrink=0.1)) #shrink是箭頭到點(diǎn)的距離
ax.axis([0, 10, 0, 10])
plt.show()
9咧七、在圖中加入圖形
流程是衰齐,先創(chuàng)建一個(gè)塊對(duì)象shp,然后通過(guò)ax.add_patch(shp)將其添加到subplot中继阻。
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
Rectangle = plt.Rectangle((0.2, 0.65), 0.5, 0.25, color='k', alpha=0.3) #矩形 (起始點(diǎn)耻涛,長(zhǎng),寬瘟檩,顏色抹缕,透明度)
Circle = plt.Circle((0.7, 0.2), 0.05, color='b', alpha=0.3) #圓形
Polygon = plt.Polygon([[0.15, 0.15], [0.25, 0.4], [0.2, 0.4]],
color='g', alpha=0.5) #多邊形
ax.add_patch(Rectangle) #加入小塊
ax.add_patch(Circle)
ax.add_patch(Polygon)
10、圖片另存為
最常用到兩個(gè)重要的參數(shù)是dpi(控制“每英寸點(diǎn)數(shù)”分辨率)和bbox_inches(剪除當(dāng)前圖表周?chē)目瞻撞糠郑?/p>
比如說(shuō)墨辛,要導(dǎo)出一張帶有小白邊且分辨率為500DPI的PNG圖片卓研,可以輸入:
# 僅僅導(dǎo)出圖片可用plt.savefig('name.png')
plt.savefig('name.png', dpi=500, bbox_inches='tight')
更多參數(shù)可參考:
11、配置matplotlib的默認(rèn)參數(shù)
可使用rc(‘希望自定義的對(duì)象’, ‘屬性’)進(jìn)行配置睹簇,例如:
plt.rc('figure', figsize=(8, 8)) # 設(shè)置圖片的默認(rèn)大小為8X8
# 還可以設(shè)置'figure'奏赘、'axes'、'xtick'带膀、'ytick'志珍、'grid'、'legend'等
# 也可以用字典的方式一次性設(shè)置
# 例如:
font_options = {'family' : 'monospace',
'weight' : 'bold',
'size' : 'small'}
plt.rc('font', **font_options)
總結(jié)
學(xué)會(huì)用matplotlib繪圖垛叨,就如同學(xué)會(huì)用PPT做展示一般伦糯,能夠更加生動(dòng)地將冰冷的數(shù)據(jù)呈現(xiàn)出來(lái),更易讓他人理解和接受自己的觀點(diǎn)嗽元。
刺猬偷腥
2018年9月30日