Seaborn是python中基于matplotlib的统计绘图模块。如果说matplotlib是“tries to make easy things easy and hard things possible”,那么seaborn则是让“hard things”也变简单。
安装
Seaborn需要python 2.7或者3.3+的环境。并且需要首先安装numpy、scipy、matplotlib和pandas模块,官网还推荐statsmodels和patsy两个模块。这些模块可以在相应官网下到,也可以在http://www.lfd.uci.edu/~gohlke/pythonlibs/网站下载(注意32/64位及对应python版本号)。
Seaborn需要在Github上下载源文件,然后在命令行运行python setup.py install即可安装到python的安装目录下。使用seaborn需要导入seaborn模块。
import seaborn as sns
以下示例均假设已经导入seaborn模块为sns。
绘图风格
Seaborn和matplotlib的区别在于,seaborn把绘图风格参数与数据参数分开设置。这样我们可以轻易的改变图像的风格。Seaborn有两组函数对风格进行控制:axes_style()/set_style()函数和plotting_context()/set_context()函数。axes_style()函数和plotting_context()函数返回参数字典,set_style()函数和set_context()函数设置matplotlib。
首先介绍第一组*_style()函数。
Seaborn有5中预定义的主题:darkgrid(灰色背景+白网格), whitegrid(白色背景+黑网格), dark(仅灰色背景), white(仅白色背景)和ticks(坐标轴带刻度)。默认的主题是darkgrid,修改主题可以使用set_style()函数。
sns.set_style(‘white’)
建议在绘制大量数据元素时,使用whitegrid主题;如果想突出带有固定模式的数据时,建议不使用网格,即dark/white主题;在体现少量特殊的数据元素结构时,使用ticks主题。
如果不需要右方和上方的坐标轴,可以使用despine()函数去掉。注意,使用despine()函数需要在画数据元素之后使用,并且despine()函数只有在使用white或ticks主题时,才会有效果。另外,despine()函数可以选择哪些坐标轴被隐藏。
sns.despine(left=True, bottom=True, right=False, top=False)
offset_spines()可以使坐标轴移开一些,远离数据元素。
使用axes_style()可以方便的临时改变绘图主题。
with sns.axes_style(‘darkgrid’):
plt.subplot(211)
plt.plot(x,y)
如果希望改变默认绘图主题的风格,可以将字典作为参数rc传入*_style()函数中。也可以使用sns.set_style(‘darkgrid’,rc)改变指定主题的风格参数。可以改变的风格参数列表可以通过sns.axes_style()的返回值得到。style的键值对列表的示例如下。
axes.labelcolor .15
axes.grid True
axes.axisbelow True
axes.edgecolor white
axes.linewidth 0
axes.facecolor #EAEAF2
font.family Arial
grid.color white
grid.linestyle -
image.cmap Greys
legend.frameon False
legend.scatterpoints 1
legend.numpoints 1
lines.solid_capst