Python可视化(二)——Seaborn

Seaborn是一个基于matplotlib的可视化库,其为用户提供了高级接口,并且该工具还深度集成了pandas的数据结构。并且该工具该集成了很多数据库,配合官网给出的代码示例,可以更方便的进行操作。

官网对它的介绍为:

Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.

Seaborn is a library for making statistical graphics in Python. It builds on top of matplotlib and integrates closely with pandas data structures.

Seaborn helps you explore and understand your data. Its plotting functions operate on dataframes and arrays containing whole datasets and internally perform the necessary semantic mapping and statistical aggregation to produce informative plots. Its dataset-oriented, declarative API lets you focus on what the different elements of your plots mean, rather than on the details of how to draw them.
官网地址为:https://seaborn.pydata.org/

提示:引入seaborn会修改matplotlib默认的颜色方案和绘图类型,以提高可读性和美观度。即使不使用seaborn API,可能也会引入seaborn,作为提高美观度和绘制常见matplotlib图形的简化方法。

和matplotlib一般被命令为plt一样,seaborn一般被命名为sns. 通常采用如下的导入方式:

import seaborn as sns

示例

这里先看一个示例:

# Import seaborn
import seaborn as sns
import pandas as pd

# Apply the default theme
sns.set_theme()

# Load an example dataset
tips = pd.read_csv(r"tips.csv")

# Create a visualization
sns.relplot(
    data=tips,
    x="total_bill", y="tip", col="time",
    hue="smoker", style="smoker", size="size",
)

首先在上面的代码中,导入了seaborn、pandas两个库。

然后set_theme()实际则是使用matplotlib rcParam系统,并对matplotlib进行配置,从而影响到最后的显示。不过上面使用的是默认配置。

除了默认配置之外,可以使用参数独立控制绘图的风格和缩放比例等。

def set_theme(context="notebook", style="darkgrid", palette="deep",
              font="sans-serif", font_scale=1, color_codes=True, rc=None):
    """
    Set aspects of the visual theme for all matplotlib and seaborn plots.

    This function changes the global defaults for all plots using the
    matplotlib rcParams system. The themeing is decomposed into several distinct
    sets of parameter values.

    The options are illustrated in the :doc:`aesthetics <../tutorial/aesthetics>`
    and :doc:`color palette <../tutorial/color_palettes>` tutorials.

    Parameters
    ----------
    context : string or dict
        Scaling parameters, see :func:`plotting_context`.
    style : string or dict
        Axes style parameters, see :func:`axes_style`.
    palette : string or sequence
        Color palette, see :func:`color_palette`.
    font : string
        Font family, see matplotlib font manager.
    font_scale : float, optional
        Separate scaling factor to independently scale the size of the
        font elements.
    color_codes : bool
        If ``True`` and ``palette`` is a seaborn palette, remap the shorthand
        color codes (e.g. "b", "g", "r", etc.) to the colors from this palette.
    rc : dict or None
        Dictionary of rc parameter mappings to override the above.

    Examples
    --------

    .. include:: ../docstrings/set_theme.rst

    """
    set_context(context, font_scale)
    set_style(style, rc={"font.family": font})
    set_palette(palette, color_codes=color_codes)
    if rc is not None:
        mpl.rcParams.update(rc)

这里和官网的示例有差异,是直接将csv文件下载到本地利用pd.read_csv()方法导入的。

之前提到seaborn和pandas关系紧密,因此能够直接使用pandas中的数据结构。

最后是使用relplot()函数创建的图表。

和matplotlib不同,seaborn的图表函数中,data参数是必须的,该参数指定了数据集,seaborn能够从该参数中推断要显示的数据。其他参数都是可选的,并且不需要指定图表元素的属性,比如颜色和标记。

数据结构

关于数据结构,使用seaborn最好是使用pandas DataFrame或者numpy array。

虽然list也可以直接使用,但是直接使用list不能发挥seaborn的优势,有点大材小用了。

data = [5,7,6,2,6,8,6,2,4,9]

sns.relplot(data, kind="line")

参数

这里看一下常用的几个参数:

  • data:表示要使用的数据集。可以是 Pandas DataFrame、NumPy 数组或其他数据结构。
  • x、y:表示要绘制的数据的变量。在大多数函数中,x 和 y 分别表示横轴和纵轴上的数据变量。
  • col:用于指定分组图表中的列变量。当需要根据数据的某个特定变量进行分组并绘制多个子图时,可以使用 col 参数。
  • hue:表示要对数据进行分组的变量,可以通过颜色或其他视觉属性来区分不同的组。
  • palette:表示要使用的颜色调色板。可以是预定义的调色板名称,也可以是自定义的颜色列表。
  • size、sizes:表示散点图中数据点的大小。size 参数控制所有数据点的大小,而 sizes 参数可以传入一个数组或列表,用于指定每个数据点的大小。
  • -style:表示散点图中数据点的样式。可以是预定义的样式名称,也可以是一个数组或列表,用于为每个数据点指定样式。
  • kind:用于指定要创建的图表类型
  • alpha:表示图表元素的透明度。可以是一个介于 0 和 1 之间的浮点数。
  • linewidth、edgecolor:表示线条的宽度和颜色。
  • bins:表示直方图中的条形数或箱线图中箱子的数量。
  • orient:表示条形图的方向,可以是 'v'(垂直)或 'h'(水平)。
  • ax:用于指定要在其上绘制图表的matplotlib Axes对象

上图总结起来就是:

  • 源数据为tips
  • x轴数据为tips中的total_bill列,y轴数据为tips中的tip列
  • 利用time列中的数据进行分组,time列中存在两类数据,分别为Lunch和Dinner,所以分为两个图
  • hue参数为smoker列,smoker列中存在两类数据,分别为Yes和No,所以每个图中又分为两类,即每个图中的数据按照Yes和No分为两类
  • style参数为smoker列,smoker列中存在两类数据,分别为Yes和No,这里用颜色区分,颜色为默认设置中的配置
  • size参数为size列,size列中存在6类,在图中就是数据点的大小不同

而kind参数主要有以下几种:

  • kind='line':折线图(Line plot)
  • kind='scatter':散点图(Scatter plot)
  • kind='bar':条形图(Bar plot)
  • kind='barh':水平条形图(Horizontal bar plot)
  • kind='hist':直方图(Histogram)
  • kind='box':箱线图(Box plot)
  • kind='violin':小提琴图(Violin plot)
  • kind='pie':饼图(Pie chart)
  • kind='heatmap':热力图(Heatmap)
  • kind='kde':核密度估计图(Kernel density plot)
  • kind='reg':线性回归图(Linear regression plot)

其它的参数也都有设置值,可查看官网或相关文档。

图表类型

从上面可以看出使用seaborn和matplotlib的区别,seaborn更加简洁,但是matplotlib更加灵活。

使用seaborn不用考虑图表的格式,线型,颜色,字体等等,只需要关注数据的分析。

而seaborn中主要的图表类型有三大类,分别是:

  • 关系图
  • 分布图
  • 分类图

其中关系图的接口为relplot(),它是一个Figure-level的函数。

在关系图中,可以使用kind参数来指定关系图的类型,例如散点图(scatter plot)、折线图(line plot)等。

另外也可以直接使用对应的接口做出对应的图形,比如:

  • relplot():创建关系图的通用函数,可以绘制散点图、折线图、小提琴图等不同类型的图表。
  • scatterplot():绘制散点图,用于显示两个连续变量之间的关系。
  • lineplot():绘制折线图,用于显示一个连续变量随另一个连续变量的变化趋势。

将上面的rellplot()函数改为scatterplot()函数,一样可以得到相同的结果,只是从美观的角度来看,没有relplot()的结果好看

import matplotlib.pyplot as plt

f, axs = plt.subplots(1, 2)

sns.scatterplot(data=tips[tips["time"] == "Dinner"], x="total_bill", y="tip", hue="smoker", style="smoker", size="size", ax=axs[0])
sns.scatterplot(data=tips[tips["time"] == "Lunch"], x="total_bill", y="tip", hue="smoker", style="smoker", size="size", ax=axs[1])

f.tight_layout()

分布图的接口为displot(),它也是一个Figure-level的函数。

在分布图中,可以使用kind参数来指定分布图的类型,例如直方图(hist plot)、核密度估计图(kde plot)、累积分布图(ecdf plot)等。

另外也可以直接使用对应的接口做出对应的图形,比如:

  • displot():绘制直方图、核密度估计图和经验累积分布函数等不同类型的单变量分布图。
  • histplot():绘制直方图,用于显示单变量的分布。
  • kdeplot():绘制核密度估计图,用于显示单变量的概率密度估计。
  • ecdfplot():绘制经验累积分布函数图,用于显示单变量的经验累积分布。
  • rugplot():绘制地毯图,用于显示单变量的数据点分布。

分类图的接口为catplot(),它也是一个Figure-level的函数。

在分类图中,可以使用kind参数来指定分布图的类型,例如条形图(bar plot)、箱线图(box plot)、小提琴图(violin plot)等。

另外也可以直接使用对应的接口做出对应的图形,比如:

  • barplot():绘制条形图,用于显示分类变量和数值变量之间的关系。
  • pointplot():绘制点图,用于显示分类变量和数值变量之间的关系,并显示置信区间。
  • boxplot():绘制箱线图,用于显示分类变量和数值变量之间的关系,并显示分位数和异常值。
  • violinplot():绘制小提琴图,用于显示分类变量和数值变量之间的关系,并显示分布和概率密度。
  • stripplot():绘制散点图,用于显示分类变量和数值变量之间的关系。
  • swarmplot():绘制蜂群图,用于显示分类变量和数值变量之间的关系,并在同一位置上显示每个数据点。

其实可以将seaborn的图像看成是matplotlib的图像,只是在matplotlib的基础上进行了美化,使用户可以关注于数据分析本身,而不是图像的细节控制。

图像的保存

既然seaborn的图像是matplotlib的图像,那么就可以使用matplotlib的保存方法来保存seaborn的图像。

plt.savefig("test.png")
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值