Seaborn:管理图表的艺术

本文介绍如何使用Seaborn模块来优化Matplotlib图表的外观。Seaborn提供了多种预设主题和高级接口,使得用户能够轻松地调整图表样式,包括背景颜色、网格线、轴脊等元素,以适应不同场合的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接
管理图表的艺术

画一个吸引人注意的图表相当重要。当你探索一个数据集,需要画图表,图表看起来令人愉悦是件很高兴的事。在与你的观众交流观点时,可视化同样重要,同时,也很有必要去让图表吸引注意力和印入脑海里。Matplotlib自动化程度非常高,但是,掌握如何设置系统以便获得一个吸引人的图是相当困难的事。为了控制matplotlib图表的外观,Seaborn模块自带许多定制的主题和高级的接口。

%matplotlib inline

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
np.random.seed(sum(map(ord, "aesthetics")))

让我们先定义一个函数用来画正弦函数,这将帮助我们了解我们可以控制的不同风格的参数

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()

https://segmentfault.com/img/bVlRPU

转换成Seaborn模块,只需要引入seaborn模块。

import seaborn as sns
sinplot()

https://i-blog.csdnimg.cn/blog_migrate/680c8572414a2f2b461da669ec5092e7.png
seaborn默认浅灰色背景与白色网络线的灵感来源于matplotlib,却比matplotlib的颜色更多柔和。我们发现,网络线对于传播信息很有用,几乎在所有情况下,人们喜欢图甚于表。默认情况下白灰网格的形式可以避免过于刺眼。在多面作图的情况下,网络形式显得相当的有利,提供了一种作图结构,这对模块中的一些复杂工具非常重要。

seaborn将matplotlib的参数划分为两个组。第一组控制图表的样式和图的度量尺度元素,这样就可以轻易在纳入到不同的上下文中。

操控这些参数由两个函数提供接口。控制样式,用axes_style()和set_style()这两个函数。度量图则用plotting_context()和set_context()这两个函数。在这两种情况下,第一组函数返回一系列的参数,第二组则设置matplotlib的默认属性。

图样式函数axes_style()和set_style()

There are five preset seaborn themes: darkgrid, whitegrid, dark, white, and ticks. They are each suited to different applications and personal preferences. The default theme is darkgrid. As mentioned above, the grid helps the plot serve as a lookup table for quantitative information, and the white-on grey helps to keep the grid from competing with lines that represent data. The whitegrid theme is similar, but it is better suited to plots with heavy data elements:

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

这里写图片描述
For many plots, (especially for settings like talks, where you primarily want to use figures to provide impressions of patterns in the data), the grid is less necessary.

sns.set_style("dark")
sinplot()

这里写图片描述

sns.set_style("white")
sinplot()

Sometimes you might want to give a little extra structure to the plots, which is where ticks come in handy:

sns.set_style("ticks")
sinplot()

这里写图片描述

Removing spines with despine()

Both the white and ticks styles can benefit from removing the top and right axes spines, which are not needed. It’s impossible to do this through the matplotlib parameters, but you can call the seaborn function despine() to remove them:
Both the white and ticks styles can benefit from removing the top and right axes spines, which are not needed. It’s impossible to do this through the matplotlib parameters, but you can call the seaborn function despine() to remove them:

sinplot()
sns.despine()

这里写图片描述

Some plots benefit from offsetting the spines away from the data, which can also be done when calling despine(). When the ticks don’t cover the whole range of the axis, the trim parameter will limit the range of the surviving spines.

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

这里写图片描述

You can also control which spines are removed with additional arguments to despine():

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

这里写图片描述

Temporarily setting figure style

Although it’s easy to switch back and forth, you can also use the axes_style() function in a with statement to temporarily set plot parameters. This also allows you to make figures with differently-styled axes:

with sns.axes_style("darkgrid"):
    plt.subplot(211)
    sinplot()
plt.subplot(212)
sinplot(-1)

http://seaborn.pydata.org/_images/aesthetics_27_0.png这里写图片描述
Overriding elements of the seaborn styles

If you want to customize the seaborn styles, you can pass a dictionary of parameters to the rc argument of axes_style() and set_style(). Note that you can only override the parameters that are part of the style definition through this method. (However, the higher-level set() function takes a dictionary of any matplotlib parameters).

If you want to see what parameters are included, you can just call the function with no arguments, which will return the current settings:

sns.axes_style()

{'axes.axisbelow': True,
 'axes.edgecolor': '.8',
 'axes.facecolor': 'white',
 'axes.grid': True,
 'axes.labelcolor': '.15',
 'axes.linewidth': 1.0,
 'figure.facecolor': 'white',
 'font.family': [u'sans-serif'],
 'font.sans-serif': [u'Arial',
  u'Liberation Sans',
  u'Bitstream Vera Sans',
  u'sans-serif'],
 'grid.color': '.8',
 'grid.linestyle': u'-',
 'image.cmap': u'Greys',
 'legend.frameon': False,
 'legend.numpoints': 1,
 'legend.scatterpoints': 1,
 'lines.solid_capstyle': u'round',
 'text.color': '.15',
 'xtick.color': '.15',
 'xtick.direction': u'out',
 'xtick.major.size': 0.0,
 'xtick.minor.size': 0.0,
 'ytick.color': '.15',
 'ytick.direction': u'out',
 'ytick.major.size': 0.0,
 'ytick.minor.size': 0.0}

You can then set different versions of these parameters:

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

这里写图片描述

Scaling plot elements with plotting_context() and set_context()

A separate set of parameters control the scale of plot elements, which should let you use the same code to make plots that are suited for use in settings where larger or smaller plots are appropriate.

First let’s reset the default parameters by calling set():

sns.set()

The four preset contexts, in order of relative size, are paper, notebook, talk, and poster. The notebook style is the default, and was used in the plots above.

sns.set_context("paper")
plt.figure(figsize=(8, 6))
sinplot()

这里写图片描述

sns.set_context("talk")
plt.figure(figsize=(8, 6))
sinplot()

这里写图片描述
../_images/aesthetics_36_0.png

sns.set_context("poster")
plt.figure(figsize=(8, 6))
sinplot()

这里写图片描述
Most of what you now know about the style functions should transfer to the context functions.

You can call set_context() with one of these names to set the parameters, and you can override the parameters by providing a dictionary of parameter values.

You can also independently scale the size of the font elements when changing the context. (This option is also available through the top-level set() function).

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

这里写图片描述
Similarly (although it might be less useful), you can temporarily control the scale of figures nested under a with statement.

Both the style and the context can be quickly configured with the set() function. This function also sets the default color palette, but that will be covered in more detail in the next section of the tutorial.

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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值