Seaborn中文教程(六):让图形更美观

让图形充满魅力是非常重要的。当我们探索一个数据集并且要进行可视化,那么,把图画得令人愉悦终究是不错的。可视化,是与听众交流大量信息时的核心方法,在这种情况下,让图形变得能瞬间抓住听众的注意非常有必要。

matplotlib支持高度的自定义,但是我们很难弄清楚应该如何调整才能让图片更具吸引力。Seaborn提供了一系列定制好的主题和一个更高级的接口,用于调整基于matplotlib的图形的外观。

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

我们来定义一个简单的函数,用来绘制一系列偏移的正弦曲线。它会帮助我们了解有哪些样式参数是可以调整的。

def sinplot(flip=1):
    x = np.linspace(0, 14, 100)
    for i in range(1, 7):
        plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)

我们先看一下matplotlib默认的风格:

sinplot()

我们可以使用set()函数来切换到seaborn的默认风格。值得注意的是,在0.8版本以前,当我们import seaborn的时候,seaborn.set()就已经被调用了,在之后的版本,我们则必须显示地调用它。

sns.set()
sinplot()

Seabornmatplotlib参数分成独立的两组。第一组用于设置图形的设计风格,第二组用于调整各种各样的图形元素,这样我们的图形就能很容易地并入不同的背景。

调整这些参数的接口是两对函数。我们可以用axes_style()或者set_style()来控制设计风格;至于控制图形元素的大小缩放,则需要使用plotting_context()set_context()函数。两种情况下,axes_*函数都会返回一个参数字典,set_*函数则会设置matplotlib的默认参数。

一、Seaborn设计风格

seaborn中有5种预设主题:darkgridwhitegriddarkwhiteticks。它们各自针对不同的应用和个人偏好。默认的主题是darkgrid。网格可以对定量信息提供参考(对照),而浅灰色则避免网格线与我们绘制的线条冲突。whitegrid主题与那些拥有很多数据元素的图很像,但是它与这种图契合得更好。

sns.set_style("whitegrid")
data = np.random.normal(size=(20, 6)) + np.arange(6) / 2
sns.boxplot(data=data);

很多情况下网格是没有必要存在的,尤其是在类似演讲的场合中,我们只想要通过图形展示某种模式的时候(这时数值参考并不重要)。

sns.set_style("dark")
sinplot()

sns.set_style("white")
sinplot()

有时我们可能想要给图形增加些额外的结构,比如增加刻度尺:

sns.set_style("ticks")
sinplot()

二、去除图形边线

whiteticks主题中,我们并不需要上边和右边的边界。我们可以使用despine()来干掉他们:

sinplot()
sns.despine()

在有些图中,我们需要调整边界与图形之间的距离,这一点我们也可以通过despine()来实现。当刻度尺不会覆盖整个坐标轴的范围时,trim参数会帮助我们限制边界的显示范围:

f, ax = plt.subplots()
sns.violinplot(data=data)
sns.despine(offset=10, trim=True);

我们也可以通过额外的参数来决定去除哪些边界:

sns.set_style("whitegrid")
sns.boxplot(data=data, palette="deep")
sns.despine(left=True);

三、临时修改设计风格

虽然我们可以很容易地改来改去,但有些情况下,我们使用with语句搭配axes_style()函数会更好。使用这种方法,我们可以在一张图的不同坐标轴中使用不同的设计:

f = plt.figure()
with sns.axes_style("darkgrid"):
    ax = f.add_subplot(1, 2, 1)
    sinplot()
ax = f.add_subplot(1, 2, 2)
sinplot(-1)

四、重载seaborn的设计元素

如果我们想定制seaborn的设计风格,我们还可以给axes_style()或者set_style()rc参数传递一个字典,这个字典由各种各样的设置项组成。需要注意的是,我们只能重载那些已经被定义好的选项。(不过更高级的set()函数可以接受任何matplotlib参数组成的字典)。

如果我们想看它们支持哪些选项,我们可以不加任何参数地调用它们,这样它们就会返回当前的配置:

sns.axes_style()
{'axes.facecolor': 'white',
 'axes.edgecolor': '.8',
 'axes.grid': True,
 'axes.axisbelow': True,
 'axes.labelcolor': '.15',
 'figure.facecolor': 'white',
 'grid.color': '.8',
 'grid.linestyle': '-',
 'text.color': '.15',
 'xtick.color': '.15',
 'ytick.color': '.15',
 'xtick.direction': 'out',
 'ytick.direction': 'out',
 'lines.solid_capstyle': 'round',
 'patch.edgecolor': 'w',
 'image.cmap': 'rocket',
 'font.family': ['sans-serif'],
 'font.sans-serif': ['Arial',
  'DejaVu Sans',
  'Liberation Sans',
  'Bitstream Vera Sans',
  'sans-serif'],
 'patch.force_edgecolor': True,
 'xtick.bottom': False,
 'xtick.top': False,
 'ytick.left': False,
 'ytick.right': False,
 'axes.spines.left': True,
 'axes.spines.bottom': True,
 'axes.spines.right': True,
 'axes.spines.top': True}

然后我们就可以进行修改和重载了:

sns.set_style("darkgrid", {"axes.facecolor": ".9"})
sinplot()

五、缩放图形元素

有一系列单独的参数可以用于控制图形元素的缩放,这样我们就可以使用同样的代码来使得我们的图片可以适应不同的应用场景(有时可能需要更大的图片,但有时却刚好相反)。

首先我们先重置所有的设置:

sns.set()

我们有四种预设的背景,按照相对大小来排序,分别是papernotebooktalkposter。上文的那些图片中使用的都是默认的notebook风格。

sns.set_context("paper")
sinplot()

sns.set_context("talk")
sinplot()

sns.set_context("poster")
sinplot()

前边我们了解的那些关于设计风格的函数的知识,大多数也适用于背景函数。

我们可以使用set_context()搭配一个背景风格的名称,也可以直接重载一个由设置选项构成的字典。

当修改了背景之后,我们也可以单独缩放字体元素(这个选项也可以通过顶级的APIset()函数来实现)。

sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
sinplot()

与设计风格相似,我们可以使用with语句临时调整图形的缩放。

不管是设计风格还是背景风格(缩放),我们都可以使用set()函数快速完成设置。这个函数还可以设置默认的调色板,不过接下来我们会更加详细地探讨关于调色板的知识。

1. 目录 1. 目录 2 2. 绘函数Plotting functions 4 2.1. 可视化的统计关系Visualizing statistical relationships 4 2.1.1. 用散点联系变量Relating variables with scatter plots 4 2.1.2. 强调线条的连续性Emphasizing continuity with line plots 10 2.1.3. 显示与切面的多个关系Showing multiple relationships with facets 21 2.2. 分类数据绘Plotting with categorical data 24 2.2.1. 分类散点Categorical scatterplots 26 2.2.2. 分类观测值分布Distributions of observations within categories 31 2.2.3. 分类统计估计Statistical estimation within categories 37 2.2.4. 对“wide-form”数据作Plotting “wide-form” data 41 2.2.5. 显示与facet的多个关系Showing multiple relationships with facets 43 2.3. 可视化数据集的分布Visualizing the distribution of a dataset 44 2.3.1. 绘制单变量分布Plotting univariate distributions 45 2.3.2. 绘制二元分布Plotting bivariate distributions 51 2.3.3. 在数据集中可视化成对关系Visualizing pairwise relationships in a dataset 55 2.4. 可视化线性关系Visualizing linear relationships 57 2.4.1. 函数绘制线性模型Functions to draw linear regression models 58 2.4.2. 拟合不同种类的模型Fitting different kinds of models 61 2.4.3. 在其他变量上的情况Conditioning on other variables 68 2.4.4. 控制表的大小和形状Controlling the size and shape of the plot 71 2.4.5. 在其他上下文中绘制回归Plotting a regression in other contexts 73 3. 多网格Multi-plot grids 76 3.1. 构建结构化的多网格Building structured multi-plot grids 76 3.2. 有条件的小倍数Conditional small multiples 77 3.3. 使用定制函数Using custom functions 86 3.4. 绘制成对的数据关系Plotting pairwise data relationships 90 4. 绘美学Plot aesthetics 99 4.1. 控制表美学Controlling figure aesthetics 99 4.1.1. Seaborn表风格Seaborn figure styles 101 4.1.2. 删除轴上的小凸起Removing axes spines 104 4.1.3. 临时设置表样式Temporarily setting figure style 105 4.1.4. 覆盖Seaborn样式的元素Overriding elements of the seaborn styles 106 4.1.5. 缩放表元素Scaling plot elements 108 4.2. 选择调色板Choosing color palettes 111 4.2.1. 创建颜色调色板Building color palettes 111 4.2.2. 定性调色板Qualitative color palettes 112 4.2.3. 连续调色板Sequential color palettes 116 4.2.4. 不同颜色的调色板Diverging color palettes 122 4.2.5. 设置默认调色板Setting the default color palette 124 5. 教程中的数据集 125
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

量化祛魅官 老Q

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值