大家都知道,Matplotlib 是眾多 Python 可視化包的鼻祖,也是Python最常用的標準可視化庫,其功能非常強大,同時也非常復雜,想要搞明白并非易事。但自從Python進入3.0時代以后,pandas的使用變得更加普及,它的身影經(jīng)常見于市場分析、爬蟲、金融分析以及科學計算中。
作為數(shù)據(jù)分析工具的集大成者,pandas作者曾說,pandas中的可視化功能比plt更加簡便和功能強大。實際上,如果是對圖表細節(jié)有極高要求,那么建議大家使用matplotlib通過底層圖表模塊進行編碼。當然,我們大部分人在工作中是不會有這樣變態(tài)的要求的,所以一句import pandas as pd就足夠應付全部的可視化工作了。
下面,我們總結一下PD庫的一些使用方法和入門技巧。
一、線型圖
對于pandas的內置數(shù)據(jù)類型,Series 和 DataFrame 都有一個用于生成各類 圖表 的 plot 方法。 默認情況下, 它們所生成的是線型圖。其實Series和DataFrame上的這個功能只是使用matplotlib庫的plot()方法的簡單包裝實現(xiàn)。參考以下示例代碼 -
import pandas as pdimport numpy as np df = pd.DataFrame(np.random.randn(10,4),index=pd.date_range('2018/12/18', periods=10), columns=list('ABCD')) df.plot()執(zhí)行上面示例代碼,得到以下結果 -

如果索引由日期組成,則調用gct().autofmt_xdate()來格式化x軸,如上圖所示。
我們可以使用x和y關鍵字繪制一列與另一列。
s = Series( np. random. randn( 10). cumsum(), index= np. arange( 0, 100, 10))s. plot()

pandas 的大部分繪圖方法都有 一個 可選的ax參數(shù), 它可以是一個 matplotlib 的 subplot 對象。 這使你能夠在網(wǎng)格 布局 中 更為靈活地處理 subplot 的位置。 DataFrame的plot 方法會在 一個 subplot 中為各列繪制 一條 線, 并自動創(chuàng)建圖例( 如圖所示):
df = DataFrame( np. random. randn( 10, 4). cumsum( 0), ...: columns=[' A', 'B', 'C', 'D'], index= np. arange( 0, 100, 10)) df. plot()

二、柱狀圖
在生成線型圖的代碼中加上 kind=' bar'( 垂直柱狀圖) 或 kind=' barh'( 水平柱狀圖) 即可生成柱狀圖。 這時,Series 和 DataFrame 的索引將會被用 作 X( bar) 或 (barh)刻度:
In [59]: fig, axes = plt. subplots( 2, 1) In [60]: data = Series( np. random. rand( 16), index= list(' abcdefghijklmnop')) In [61]: data. plot( kind=' bar', ax= axes[ 0], color=' k', alpha= 0. 7) Out[ 61]: < matplotlib. axes. AxesSubplot at 0x4ee7750> In [62]: data. plot( kind=' barh', ax= axes[ 1], color=' k', alpha= 0.
新聞熱點
疑難解答