干货:用Python玩转数据可视化,炫酷图表是这样做出来的

导读:相比于科学,数据分析更像是一门艺术。创建样式优美的数据可视化是这个艺术中不可缺少的部分。然而,某些人认为优美的,也会有人觉得难以接受。和艺术类似,随着数据分析的快速演变,人们的观念和品味也一直在变化。但是总的来说没有人是绝对正确和错误的。

作为一个数据艺术家以及有经验的Python程序员,我们可以从matplotlib、Seaborn、Bokeh和ggplot这些库里面选择一些来使用。

作者:伊凡·伊德里斯(Ivan Idris)

如需转载请联系华章科技

01 图形化安斯库姆四重奏

安斯库姆四重奏(Anscombe's Quartet)是一个经典案例,它可以说明为什么可视化是很重要的。四重奏包含了四组统计特性一致的数据。每个数据集有一些x值以及相对应的y值,我们将在一个IPython Notebook中列出这些指标。如果你绘制出这些数据集,你将发现这些图表截然不同。

  • 操作步骤

在本节你需要执行如下操作:

(1)由如下导入开始:

import pandas as pd 
import seaborn as sns 
import matplotlib.pyplot as plt 
import matplotlib as mpl 
from dautil import report 
from dautil import plotting 
import numpy as np 
from tabulate import tabulate

(2)定义以下函数来计算某一数据集中x和y的均值和方差、相关系数,以及斜率和每个数据集的线性拟合的截距:

def aggregate():
 df = sns.load_dataset("anscombe")
 agg = df.groupby('dataset') 
 .agg([np.mean, np.var]) 
 .transpose()
 groups = df.groupby('dataset')
 corr = [g.corr()['x'][1] for _, g in groups]
 builder = report.DFBuilder(agg.columns)
 builder.row(corr)
 fits = [np.polyfit(g['x'], g['y'], 1) for _, g in groups] 
 builder.row([f[0] for f in fits]) 
 builder.row([f[1] for f in fits]) 
 bottom = builder.build(['corr', 'slope', 'intercept'])
 return df, pd.concat((agg, bottom))

(3)下面这个函数返回一个字符串,这个字符串有一部分是Markdown,有一部分是重组的文字,有一部分是HTML,这主要是因为原生的Markdown不支持图表:

def generate(table):
 writer = report.RSTWriter()
 writer.h1('Anscombe Statistics')
 writer.add(tabulate(table, tablefmt='html', floatfmt='.3f'))
 return writer.rst

(4)绘制数据并相应地与Seaborn的lmplot()函数线性拟合:

def plot(df):
 sns.set(style="ticks")
 g = sns.lmplot(x="x", y="y", col="dataset",
 hue="dataset", data=df,
 col_wrap=2, ci=None, palette="muted", size=4,
 scatter_kws={"s": 50, "alpha": 1})
 plotting.embellish(g.fig.axes)

(5)展示一个统计数据的表格如下:

df, table = aggregate()
from IPython.display import display_markdown
display_markdown(generate(table), raw=True)

下表中显示每个数据集的几乎相同的统计数据(我修改了IPython配置文件里的 custom.css,所以下表是有颜色的):

干货:用Python玩转数据可视化,炫酷图表是这样做出来的

 

(6)以下几行代码绘制了数据集:

%matplotlib inline
plot(df)

请参见以下截图了解最终结果:

干货:用Python玩转数据可视化,炫酷图表是这样做出来的

 

02 选择Seaborn的调色板

Seaborn的调色板和matplotlib的颜色表类似。色彩可以帮助你发现数据中的模式,也是重要的可视化组成部分。Seaborn有很丰富的调色板,在这个示例中会将其可视化。

  • 操作步骤

(1)导入部分如下:

import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from dautil import plotting

(2)使用以下函数帮助绘制调色板:

def plot_palette(ax, plotter, pal, i, label, ncol=1):
 n = len(pal)
 x = np.linspace(0.0, 1.0, n)
 y = np.arange(n) + i*n
 ax.scatter(x, y, c=x,
 cmap=mpl.colors.ListedColormap(list(pal)), 
 s=200)
 plotter.plot(x,y,label=label)
 handles, labels = ax.get_legend_handles_labels()
 ax.legend(loc='best', ncol=ncol, fontsize=18)

(3)分类调色板(categorical palette)对于分类数据很有用,例如性别、血型等。以下函数可以绘制一些Seaborn的分类调色板:

def plot_categorical_palettes(ax):
 palettes = ['deep', 'muted', 'pastel', 'bright', 'dark','colorblind']
 plotter = plotting.CyclePlotter(ax)
 ax.set_title('Categorical Palettes')
 for i, p in enumerate(palettes):
 pal = sns.color_palette(p)
 plot_palette(ax, plotter, pal, i, p, 4)

(4)圆形色彩系统(circular color system)通常用HLS(色度亮度饱和度,Hue Lightness Saturation)来取代RGB(红绿蓝Red Gree Blue)颜色空间。如果你有很多分类这将会很有用。以下函数可以使用HLS系统绘制调色板。

def plot_circular_palettes(ax):
 ax.set_title('Circular Palettes')
 plotter = plotting.CyclePlotter(ax)
 pal = sns.color_palette("hls", 6)
 plot_palette(ax, plotter, pal, 0, 'hls')
 sns.hls_palette(6, l=.3, s=.8)
 plot_palette(ax, plotter, pal, 1, 'hls l=.3 s=.8')
 pal = sns.color_palette("husl", 6)
 plot_palette(ax, plotter, pal, 2, 'husl')
 sns.husl_palette(6, l=.3, s=.8)
 plot_palette(ax, plotter, pal, 3, 'husl l=.3 s=.8') 

(5)Seaborn也有基于在线的ColorBrewer工具的调色板(http://colorbrewer2.org/)。用以下函数绘制出来:

def plot_brewer_palettes(ax):
 ax.set_title('Brewer Palettes')
 plotter = plotting.CyclePlotter(ax)
 pal = sns.color_palette("Paired")
 plot_palette(ax, plotter, pal, 0, 'Paired')
 pal = sns.color_palette("Set2", 6)
 plot_palette(ax, plotter, pal, 1, 'Set2')

(6)连续调色板(sequential palettes)对于数据范围很广的数据来说很有用,比如说有数量级差异的数据。用以下函数绘制出来:</

  • 6
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值