1.Python基本功能
- 利用Python写脚本
- excel可视化有性能瓶颈,需要Python来实现。
- 安装(建议Anaconda)
2.Numpy和pandas
(1)numpy
(2)pandas
- 数据读取:pd.read_csv(默认utf-8)、info、head、tail、top、astype、query、
- 数据筛选:sort_values、rank、cut、qcut(分位法)、
- Python groupby :mysql不支持分组排序
- 关联:concat和merge:concat是强行耦合,merge,是有共同名,优先表进行耦合
- 多重索引
- 文本函数:填充空值,None需要用np.nan,c语言形式的控制;
- 去重:pd.dropna()去除所有还有空值的行
- Python pandas apply
- 聚合 apply
- pandas数据透视
- python连接数据库
3.数据可视化
概率:
- distplot 概率分布图
- kdeplot 概率密度图
- jointplot 联合密度图
- pairplot 多变量图
分类:
boxplot
箱线图violinplot
提琴图barplot
柱形图factorplot
因子图
线性:
- Implot 回归图
- heatmap 热图
案例:seaborn可视化学习之categorial visualization
seaborn是一个做数据可视化效果很棒的库。在看了官方tutorial之后,尝试用Iris鸢尾花数据集实践一下categorical visualization,也就是数据按类别进行可视化。
首先介绍一下Iris鸢尾花数据集,内容摘自百度百科:Iris数据集是常用的分类实验数据集,由Fisher, 1936收集整理。“Iris也称鸢尾花卉数据集,是一类多重变量分析的数据集。数据集包含150个数据集,分为3类,每类50个数据,每个数据包含4个属性。可通过花萼长度,花萼宽度,花瓣长度,花瓣宽度4个属性预测鸢尾花卉属于(Setosa,Versicolour,Virginica)三个种类中的哪一类”。
导入库
In [1]:
import warnings warnings.filterwarnings("ignore") import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns
In [2]:
ls ../input/iris/
iris/ iris.csv
读取数据
In [3]:
iris = pd.read_csv('../input/iris/iris.csv') iris.head()
Out[3]:
Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species | |
---|---|---|---|---|---|
0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa |
1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa |
2 | 4.7 | 3.2 | 1.3 | 0.2 | setosa |
3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa |
4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa |
数据字段介绍:
- sepal_length:花萼长度,单位cm
- sepal_width:花萼宽度,单位cm
- petal_length:花瓣长度,单位cm
- petal_width:花瓣宽度,单位cm
- 种类:setosa(山鸢尾),versicolor(杂色鸢尾),virginica(弗吉尼亚鸢尾)
在做categorical visualization的时候,seaborn给出了基础的stripplot & swarmplot, boxplot & violinplot, barplot & pointplot,以及抽象化的factorplot.下面就用纸鸢花数据集做一下讲解。
Stripplot
Stripplot的本质就是把数据集中具有quantitative属性的变量按照类别去做散点图(Scatterplot)。
我们将纸鸢花数据集中不同种类花的sepal length做stripplot可视化
In [4]:
plt.figure(1,figsize=(12,6)) plt.subplot(1,2,1) sns.stripplot(x='Species',y='Sepal.Length',data=iris) #stripplot plt.title('Striplot of sepal length of Iris species') with sns.axes_style("whitegrid"): # 这个是临时设置样式的命令,如果不写,则按默认格式'darkgrid'进行绘制 plt.subplot(1,2,2) plt.title('Striplot of sepal length of Iris species') sns.stripplot(x='Species',y='Sepal.Length',data=iris,jitter=True) # jitterplot plt.show()
上边左侧的图片便是在默认风格下用stripplot绘制的散点图。在很多情况下,stripplot中的点会重叠,使得我们不容易看出点的分布情况。一个简单的解决办法就是用在stripplot的基础上绘制抖动图(jitterplot),仅沿着类别坐标轴的方向去随机微调整点的位置,显示出分布情况。
Swarmplot
另一个解决stripplot中点重叠的办法就是绘制swarmplot,它的本质就是用通过算法,在类别坐标轴的方向上去‘延展’绘制这些原本重合的点。 我们将纸鸢花数据集中不同种类花的petal length和petal width做swarmplot可视化。
In [5]:
plt.figure(1,figsize=(12,6)) plt.subplot(1,2,1) sns.swarmplot(x='Species',y='Petal.Length',data=iris) with sns.axes_style("ticks"): # 这次使用了ticks风格 plt.subplot(1,2,2) sns.swarmplot(x='Species',y='Petal.Width',data=iris) plt.show()
Boxplot
箱形图,主要包含六个数据节点,将一组数据从大到小排列,分别计算出上边缘,上四分位数Q3,中位数,下四分位数Q1,下边缘,还有异常值。 下面将纸鸢花数据集中的四个变量sepal_length, sepal_width, petal_length和petal_width做箱形图可视化。
In [6]:
var = ['Sepal.Length','Sepal.Width','Petal.Length','Petal.Width'] axes_style = ['ticks','white','whitegrid', 'dark'] fig = plt.figure(1,figsize=(12,12)) for i in range(4): with sns.axes_style(axes_style[i]): # 将除了默认的darkgrid之外的样式都展现一遍 plt.subplot(2,2,i+1) sns.boxplot(x='Species',y=var[i],data=iris) plt.show()
Violinplot
Violinplot相当于结合了箱形图与核密度图,更好地展现出数据的量化形态。展示如下:
In [7]:
context= ['notebook','paper','talk','poster'] axes_style = ['ticks','white','whitegrid', 'dark'] plt.figure(1,figsize=(12,12)) for i in range(4): with sns.axes_style(axes_style[i]):#设置axes_style sns.set_context(context[i]) # 设置context style,默认为notebook,除此之外还有paper,talk,poster plt.subplot(2,2,i+1) plt.title(str(var[i])+ ' in Iris species') sns.violinplot(x='Species',y=var[i],data=iris) plt.show()
Violinplot用kernel density estimate去更好地描述了quantitative变量的分布。
与此同时,也可以组合swarmplot和boxplot或violinplot去描述quantitative变量。用鸢尾花数据集展示如下:
In [8]:
context= ['notebook','paper','talk','poster'] axes_style = ['ticks','white','whitegrid', 'dark'] plt.figure(1,figsize=(12,12)) for i in range(4): with sns.axes_style(axes_style[i]):#设置axes_style sns.set_context(context[i])#设置context plt.subplot(2,2,i+1) plt.title(str(var[i])+ ' in Iris species') sns.swarmplot(x='Species', y=var[i], data=iris, color="w", alpha=.5) sns.violinplot(x='Species', y=var[i], data=iris, inner=None) if i%2 ==0 \ else sns.boxplot(x='Species', y=var[i], data=iris) # 分别用swarmplot+violinplot 和swarmplot + boxplot plt.show()
Barplot
Barplot主要是展现在分类中的quantitative变量的平均值情况,并且用了boostrapping算法计算了估计值的置信区间和error bar.用鸢尾花数据集展示如下:
In [9]:
plt.figure(1,figsize=(12,12)) for i in range(4): with sns.axes_style(axes_style[i]):#设置axes_style sns.set_context(context[i]) # 设置context style,默认为notebook,除此之外还有paper,talk,poster plt.subplot(2,2,i+1) plt.title(str(var[i])+ ' in Iris species') sns.barplot(x='Species',y=var[i],data=iris) plt.show()
Countplot
如果想知道在每个类别下面有多少个观察值,用countplot就可以,相当于是做一个observation counts,用鸢尾花数据集展示如下:
In [10]:
plt.figure(figsize=(5,5)) sns.countplot(y="Species", data=iris) # 设置y='species',将countplot水平放置 plt.title('Iris species count') plt.show()
Pointplot
Pointplot相当于是对barplot做了一个横向延伸,一方面,用point estimate和confidence level去展示barplot的内容;另一方面,当每一个主类别下面有更细分的sub-category的时候,pointplot可以便于观察不同sub-category在各主类别之间的联系。展示如下:
In [11]:
plt.figure(1,figsize=(12,12)) for i in range(4): with sns.axes_style(axes_style[i]):#设置axes_style sns.set_context(context[i]) # 设置context style,默认为notebook,除此之外还有paper,talk,poster plt.subplot(2,2,i+1) plt.title(str(var[i])+ ' in Iris species') sns.pointplot(x='Species',y=var[i],data=iris) plt.show()
Factorplot
Factorplot可以说是seaborn做category visualization的精髓,前面讲的这些plot都可以说是factorplot的具体展示。我们可以用PariGrid去实现对多个类别的数值特征用同一种plot做可视化。
In [12]:
sns.set(style="ticks") g = sns.PairGrid(iris, x_vars = ['Sepal.Length','Sepal.Width','Petal.Length','Petal.Width'], y_vars = 'Species', aspect=0.75,size=4) # 设置间距和图片大小 g.map(sns.violinplot,palette='pastel') plt.show()
附上各plot function的API,今后将会对API中的参数结合tutorial讲讲,如何做出更好的可视化效果。更新ing
seaborn.stripplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, jitter=False, dodge=False, orient=None, color=None, palette=None, size=5, edgecolor='gray', linewidth=0, ax=None, **kwargs)
seaborn.swarmplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, dodge=False, orient=None, color=None, palette=None, size=5, edgecolor='gray', linewidth=0, ax=None, **kwargs)
seaborn.boxplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, width=0.8, dodge=True, fliersize=5, l inewidth=None, whis=1.5, notch=False, ax=None, **kwargs)
seaborn.violinplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, bw='scott', cut=2, scale='area', scale_hue=True, gridsize=100, width=0.8, inner='box', split=False, dodge=True, orient=None, linewidth=None, color=None, palette=None, saturation=0.75, ax=None, **kwargs)
seaborn.lvplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, width=0.8, dodge=True, k_depth='proportion', linewidth=None, scale='exponential', outlier_prop=None, ax=None, **kwargs)
seaborn.pointplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, estimator=<function mean>, ci=95, n_boot=1000, units=None, markers='o', linestyles='-', dodge=False, join=True, scale=1, orient=None, color=None, palette=None, errwidth=None, capsize=None, ax=None, **kwargs)
seaborn.barplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, estimator=<function mean>, ci=95, n_boot=1000, units=None, orient=None, color=None, palette=None, saturation=0.75, errcolor='.26', errwidth=None, capsize=None, dodge=True, ax=None, **kwargs)
小结
seaborn是一个很棒的可视化库,尤其是当数据维度很大的时候,seaborn可以让我们用最少的代码去绘制一些描述性统计的图,便于找寻各维度变量之间的特征。此篇文档也是我对seaborn的学习笔记,这次整理的内容是关于category visualization。下次将会选取其他数据集去整理关于distribution visualization的内容。
4.案例实战分析
https://www.kesci.com/apps/home/project/5aa687afcbc87e3f21332885
5.数据分析平台
本次使用的是Python中的superset库,基于web的数据分析平台。
严重提示:安装这个库一定要新建一个虚拟环境后再进行pip安装,不然会使得依赖库和Anaconda中的部分库冲突,使得原环境的库无法正常调用
使用逻辑:
- 先加载数据库或者数据文件
- 写好sql语法,进行一定编辑数据集。
- 在silces里面对于数据集,进行一个个图的绘画与调整
- Dashboard里进行最后图表的汇合。