09 炫酷的可視化工具包——cufflinks


前言

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

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

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

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

cufflinks介紹

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

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

安裝

pip install cufflinks

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實例

注意:以下圖例都是動態圖,無法放置gif圖,可以自己嘗試一下

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

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

cf.set_config_file(offline=True)
    <script type="text/javascript">
    window.PlotlyConfig = {MathJaxConfig: 'local'};
    if (window.MathJax) {MathJax.Hub.Config({SVG: {font: "STIX-Web"}});}
    if (typeof require !== 'undefined') {
    require.undef("plotly");
    requirejs.config({
        paths: {
            'plotly': ['https://cdn.plot.ly/plotly-latest.min']
        }
    });
    require(['plotly'], function(Plotly) {
        window._Plotly = Plotly;
    });
    }
    </script>

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

lines線圖

1)cufflinks使用datagen生成隨機數;
2)figure定義為lines形式,數據為(1,500);
3)然后再用ta_plot繪制這一組時間序列,參數設置SMA展現三個不同周期的時序分析。

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

box箱型圖

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

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

cf.datagen.box(10)

ZZQ.IX KKT.HE WUI.GF KUD.YP LVO.BR RIQ.OH HCY.AX TSI.WB CZC.FE PGJ.UN
0 2.650637 2.860086 0.648258 0.453637 0.031173 1.588635 0.665888 1.322199 0.613859 1.887332
1 1.772565 1.223209 1.321523 5.185581 4.585844 2.950900 0.652469 0.471112 5.729238 3.034579
2 3.707357 5.745729 5.766174 1.785150 8.335558 17.388996 2.854110 5.725720 9.582913 1.221468
3 9.298724 8.008446 2.574685 3.924959 5.656232 8.797833 18.606412 10.594716 1.207231 3.901563
4 5.261365 3.498773 4.593977 6.516262 3.852370 3.402193 2.813485 2.340898 7.611254 5.423463
... ... ... ... ... ... ... ... ... ... ...
95 0.136329 2.676648 0.403378 1.018672 1.447996 1.106163 1.563319 6.315881 1.148427 0.348217
96 4.243743 0.026604 0.442303 2.650356 7.911090 1.048235 3.231528 0.850884 0.336564 0.301514
97 2.223366 3.581352 2.712159 1.141006 1.841442 4.167166 10.543993 5.589251 12.338148 4.013969
98 1.391020 0.002552 0.177377 1.865509 0.690297 0.682517 7.477029 0.261913 0.020654 0.822866
99 0.229824 1.756769 1.782207 3.621471 1.523997 4.392876 0.403206 6.899078 1.268289 7.484547

100 rows × 10 columns

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 散點矩陣圖

df = pd.DataFrame(np.random.randn(1000, 4), columns=['a', 'b', 'c', 'd'])
df.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)


免責聲明!

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



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