【Python學習】cufflinks模塊


學過Python數據分析的朋友都知道,在可視化的工具中,有很多優秀的三方庫,比如matplotlibseabornplotlyBokenpyecharts等等。這些可視化庫都有自己的特點,在實際應用中也廣為大家使用。

plotly、Boken等都是交互式的可視化工具,結合Jupyter notebook可以非常靈活方便地展現分析后的結果。雖然做出的效果非常的炫酷,比如plotly,但是每一次都需要寫很長的代碼,一是麻煩,二是不便於維護。

我覺得在數據的分析階段,更多的時間應該放在分析上,維度選擇、拆解合並,業務理解和判斷。如果既可以減少代碼量,又可以做出炫酷可視化效果,那將大大提高效率。當然如果有特別的需求除外,此方法僅針對想要快速可視化進行分析的人。

本篇給大家介紹一個非常棒的工具,cufflinks,可以完美解決這個問題,且效果一樣炫酷。

cufflinks介紹

就像seaborn封裝了matplotlib一樣,cufflinks在plotly的基礎上做了一進一步的包裝,方法統一,參數配置簡單。其次它還可以結合pandas的dataframe隨意靈活地畫圖。可以把它形容為"pandas like visualization"。

毫不誇張地說,畫出各種炫酷的可視化圖形,我只需一行代碼,效率非常高,同時也降低了使用的門檻兒。cufflinks的github鏈接如下:

https://github.com/santosjorg…

cufflinks安裝

安裝不多說,直接pip install即可。

pip install cufflinks
pip install chart-studio

cufflinks如何使用?

cufflinks庫一直在不斷更新,目前最新版為V0.14.0,支持plotly3.0。首先我們看看它都支持哪些種類的圖形,可以通過help來查看。

import cufflinks as cf
cf.help()

Use 'cufflinks.help(figure)' to see the list of available parameters for the given figure.
Use 'DataFrame.iplot(kind=figure)' to plot the respective figure
Figures:
  bar
  box
  bubble
  bubble3d
  candle
  choroplet
  distplot
  heatmap
  histogram
  ohlc
  pie
  ratio
  scatter
  scatter3d
  scattergeo
  spread
  surface
  violin

使用方法其實很簡單,我總結一下,它的格式大致是這樣的:



  • DataFrame:代表pandas的數據框;
  • Figure:代表我們上面看到的可繪制圖形,比如bar、box、histogram等等;
  • iplot:代表繪制方法,其中有很多參數可以進行配置,調節符合你自己風格的可視化圖形;

 

cufflinks實例

我們通過幾個實例感受一下上面的使用方法。使用過plotly的朋友可能知道,如果使用online模式,那么生成的圖形是有限制的。所以,我們這里先設置為offline模式,這樣就避免了出現次數限制問題。

import pandas as pd
import cufflinks as cf
import numpy as np

cf.set_config_file(offline=True)

然后我們需要按照上面的使用格式來操作,首先我們需要有個DataFrame,如果手頭沒啥數據,那可以先生成個隨機數。cufflinks有一個專門生成隨機數的方法,叫做datagen,用於生成不同維度的隨機數據,比如下面。

解決 AttributeError: module ‘plotly.offline‘ has no attribute ‘__PLOTLY_OFFLINE_INITIALIZED‘

https://blog.csdn.net/acdefghb/article/details/107412152

lines線圖

cf.datagen.lines(1,500).ta_plot(study='sma',periods=[13,21,55])

1)cufflinks使用datagen



box箱型圖

還是與上面用法一樣,一行代碼解決。

 cf.datagen.box(20).iplot(kind='box',legend=False)
 



可以看到,x軸每個box都有對應的名稱,這是因為cufflinks通過kind參數識別了box圖形,自動為它生成的名字。如果我們只生成隨機數,它是這樣子的,默認生成100行的隨機分布的數據,列數由自己選定。



histogram直方圖

 cf.datagen.histogram(3).iplot(kind='histogram')
 



和plotly一樣,我們可以通過一些輔助的小工具框選或者lasso選擇來區分和選定指定區域,只要一行代碼。

當然了,除了隨機數據,任何的其它dataframe數據框都可以,包括我們自己導入的數據。

histogram條形圖

df=pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.iplot(kind='bar',barmode='stack')
 



上面我們生成了一個(10,4)的dataframe數據框,名稱分別是a,b,c,d。那么cufflinks將會根據iplot中的kind種類自動識別並繪制圖形。參數設置為堆疊模式。


scatter散點圖

df = pd.DataFrame(np.random.rand(50, 4), columns=['a', 'b', 'c', 'd'])
df.iplot(kind='scatter',mode='markers',colors=['orange','teal','blue','yellow'],size=10)
 



bubble氣泡圖

df.iplot(kind='bubble',x='a',y='b',size='c')
 



scatter matrix 散點矩陣圖

 



subplots 子圖

df=cf.datagen.lines(4)
df.iplot(subplots=True,shape=(4,1),shared_xaxes=True,vertical_spacing=.02,fill=True)
 
df.iplot(subplots=True,subplot_titles=True,legend=False)
 



再比如復雜一點的。

df=cf.datagen.bubble(10,50,mode='stocks')
figs=cf.figures(df,[dict(kind='histogram',keys='x',color='blue'),
                    dict(kind='scatter',mode='markers',x='x',y='y',size=5),
                    dict(kind='scatter',mode='markers',x='x',y='y',size=5,color='teal')],asList=True)
figs.append(cf.datagen.lines(1).figure(bestfit=True,colors=['blue'],bestfit_colors=['pink']))
base_layout=cf.tools.get_base_layout(figs)
sp=cf.subplots(figs,shape=(3,2),base_layout=base_layout,vertical_spacing=.15,horizontal_spacing=.03,
               specs=[[{'rowspan':2},{}],[None,{}],[{'colspan':2},None]],
               subplot_titles=['Histogram','Scatter 1','Scatter 2','Bestfit Line'])
sp['layout'].update(showlegend=False)
cf.iplot(sp)



shapes 形狀圖


如果我們想在lines圖上增加一些直線作為參考基准,這時候我們可以使用hlines的類型圖。

df=cf.datagen.lines(3,columns=['a','b','c'])
df.iplot(hline=[dict(y=-1,color='blue',width=3),dict(y=1,color='pink',dash='dash')])
 



或者是將某個區域標記出來,可以使用hspan類型。


df.iplot(hspan=[(-1,1),(2,5)])



又或者是豎條的區域,可以用vspan類型。

df.iplot(vspan={'x0':'2015-02-15','x1':'2015-03-15','color':'teal','fill':True,'opacity':.4})



如果對iplot中的參數不熟練,直接輸入以下代碼即可查詢。

 help(df.iplot)


總結


怎么樣,是不是非常快捷方便?以上介紹是一般的可繪制類型,當然你可以根據自己的需求做出更多的可視化圖形。如果是常規圖形,一行即可實現。除此外,cufflinks還有強大的顏色管理功能,如果感興趣可以自行學習。

成長離不開與優秀的同伴共同交流,如果你需要好的學習環境,好的學習資源,這里歡迎每一位熱愛Python的小伙伴,Python學習圈

發布於 2019-09-28 22:17
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM