共计 3911 个字符,预计需要花费 10 分钟才能阅读完成。
作者:xiaoyu
微信公众号:Python 数据科学
知乎:python 数据分析师
前言
学过 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/santosjorg…
cufflinks 安装
安装不多说,直接 pip install 即可。
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 实例
我们通过几个实例感受一下上面的使用方法。使用过 plotly 的朋友可能知道,如果使用 online 模式,那么生成的图形是有限制的。所以,我们这里先设置为 offline 模式,这样就避免了出现次数限制问题。
import pandas as pd | |
import cufflinks as cf | |
import numpy as np | |
cf.set_config_file(offline=True) |
然后我们需要按照上面的使用格式来操作,首先我们需要有个 DataFrame,如果手头没啥数据,那可以先生成个随机数。cufflinks 有一个专门生成随机数的方法,叫做datagen
,用于生成不同维度的随机数据,比如下面。
lines 线图
cf.datagen.lines(1,500).ta_plot(study='sma',periods=[13,21,55])
1)cufflinks 使用 datagen 生成随机数;
2)figure 定义为 lines 形式,数据为(1,500);
3)然后再用 ta_plot 绘制这一组时间序列,参数设置 SMA 展现三个不同周期的时序分析。
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 散点矩阵图
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)
总结
怎么样,是不是非常快捷方便?以上介绍是一般的可绘制类型,当然你可以根据自己的需求做出更多的可视化图形。如果是常规图形,一行即可实现。除此外,cufflinks 还有强大的颜色管理功能,如果感兴趣可以自行学习。
如果觉得有帮助,还请给点个赞!
欢迎关注我的个人公众号:Python 数据科学