1 箱形图Boxplot

(代码下载)
Boxplot可能是最常见的图形类型之一。它能够很好表示数据中的分布规律。箱型图方框的末尾显示了上下四分位数。极线显示最高和最低值,不包括异常值。seaborn中用boxplot函数制作箱形图。该章节主要内容有:

  1. 基础箱形图绘制 Basic boxplot and input format
  2. 自定义外观 Custom boxplot appearance
  3. 箱型图的颜色设置 Control colors of boxplot
  4. 分组箱图 Grouped Boxplot
  5. 箱图的顺序设置 Control order of boxplot
  6. 添加散点分布 Add jitter over boxplot
  7. 显示各类的样本数 Show number of observation on boxplot
  8. 箱形图隐藏的数据处理 Hidden data under boxplot
#调用seaborn
import seaborn as sns
#调用seaborn自带数据集
df = sns.load_dataset('iris')
#显示数据集
df.head()
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa

1. 基础箱形图绘制 Basic boxplot and input format

  • 一个数值变量 One numerical variable only
  • 一个数值变量和多个分组 One numerical variable, and several groups
  • 多个数值变量 Several numerical variable
  • 水平箱型图 Horizontal boxplot with seaborn
# 一个数值变量 One numerical variable only
# 如果您只有一个数字变量,则可以使用此代码获得仅包含一个组的箱线图。
# Make boxplot for one group only
# 显示花萼长度sepal_length
sns.boxplot( y=df["sepal_length"] );

# 一个数值变量和多个分组 One numerical variable, and several groups
# 假设我们想要研究数值变量的分布,但是对于每个组分别进行研究。在这里,我们研究了3种花的萼片长度。
# x花的品种,y花萼长度
sns.boxplot( x=df["species"], y=df["sepal_length"] );

# 多个数值变量 Several numerical variable
# 可以研究几个数值变量的分布,比如说萼片的长度和宽度:
sns.boxplot(data=df.iloc[:,0:2]);

# 水平箱型图 Horizontal boxplot with seaborn
# 用seaborn将你的箱图水平转动是非常简单的。您可以切换x和y属性,或使用选项orient ="h"
sns.boxplot( y=df["species"], x=df["sepal_length"] );

2. 自定义外观 Custom boxplot appearance

  • 自定义线宽 Custom line width
  • 添加缺口 Add notch
  • 控制箱的尺寸 Control box sizes
# 自定义线宽 Custom line width
# Change line width
# 根据linewidth改变线条宽度
sns.boxplot( x=df["species"], y=df["sepal_length"], linewidth=5);

# 添加缺口 Add notch
# notch设置为true即可
sns.boxplot( x=df["species"], y=df["sepal_length"], notch=True);

# 控制箱的尺寸 Control box sizes
# Change width
sns.boxplot( x=df["species"], y=df["sepal_length"], width=0.3);

3. 箱型图的颜色设置 Control colors of boxplot

  • 调色板的使用 Use a color palette
  • 单种颜色的使用 Uniform color
  • 每组的特定颜色 Specific color for each group
  • 单组高亮 Highlight a group
  • 添加透明色 Add transparency to color
# 调色板的使用 Use a color palette
# Python提出了几种调色板。您可以像Set1,Set2,Set3,Paired,BuPu一样调用RColorBrewer调色板,还有Blues或BuGn_r等调色板。
# 调色板各种颜色见 http://www.r-graph-gallery.com/38-rcolorbrewers-palettes/
# t通过plaette调用调色板,Use a color palette
sns.boxplot( x=df["species"], y=df["sepal_length"], palette="Blues");

# 单种颜色的使用 Uniform color
# 当然您可以轻松地为每个盒子应用同样的颜色。最常见的是b: blue
# 颜色列表 https://matplotlib.org/examples/color/named_colors.html
sns.boxplot( x=df["species"], y=df["sepal_length"], color="skyblue");

# 每组的特定颜色 Specific color for each group
# 用不用颜色描绘不同种类的花
my_pal = {"versicolor": "g", "setosa": "b", "virginica":"m"}
sns.boxplot( x=df["species"], y=df["sepal_length"], palette=my_pal);

# 单组高亮 Highlight a group
# 设定某一组为红色,其他组为蓝色
my_pal = {species: "r" if species == "versicolor" else "b" for species in df.species.unique()}
sns.boxplot( x=df["species"], y=df["sepal_length"], palette=my_pal);

# 添加透明色 Add transparency to color
# usual boxplot 正常绘图
ax = sns.boxplot(x='species', y='sepal_length', data=df);
# Add transparency to colors 设置透明色
for patch in ax.artists:
r, g, b, a = patch.get_facecolor()
patch.set_facecolor((r, g, b, .3))

4. 分组箱图 Grouped Boxplot

# 当您有一个数值变量,几个组和子组时,将使用分组箱图。使用seaborn很容易实现。Y是您的数字变量,x是组列,而hue是子组列。
# 调用tips数据集
df_tips = sns.load_dataset('tips')
df_tips.head()
total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
# Grouped boxplot 分组箱图
# x日期,y餐费,hue自组列,palette调色盘
sns.boxplot(x="day", y="total_bill", hue="smoker", data=df_tips, palette="Set1");

5. 箱图的顺序设置 Control order of boxplot

#如果您按特定顺序设定组,则箱图通常会提供更多信息。这对seaborn来说是可行的。
# specific order 通过order自定义组
p1=sns.boxplot(x='species', y='sepal_length', data=df, order=["virginica", "versicolor", "setosa"]);

# 中位数由大到小排列
# Find the order 设定中位数
my_order = df.groupby(by=["species"])["sepal_length"].median().iloc[::-1].index
# Give it to the boxplot
sns.boxplot(x='species', y='sepal_length', data=df, order=my_order);

6. 添加散点分布 Add jitter over boxplot

# 可以在箱线图上添加每种类别的散点分布情况
# Usual boxplot 正常绘图
ax = sns.boxplot(x='species', y='sepal_length', data=df)
# Add jitter with the swarmplot function 添加散点分布
ax = sns.swarmplot(x='species', y='sepal_length', data=df, color="grey")

7. 显示各类的样本数 Show number of observation on boxplot

# 显示每个组的观察次数可能很有用

# 基础的箱形图
ax = sns.boxplot(x="species", y="sepal_length", data=df) # Calculate number of obs per group & median to position labels
# 计算各个种类的中位数
medians = df.groupby(['species'])['sepal_length'].median().values
# 统计各个种类的样本数
nobs = df['species'].value_counts().values
nobs = [str(x) for x in nobs.tolist()]
nobs = ["n: " + i for i in nobs] # Add it to the plot
pos = range(len(nobs))
for tick,label in zip(pos,ax.get_xticklabels()):
ax.text(pos[tick], medians[tick] + 0.03, nobs[tick], horizontalalignment='center', size='x-small', color='w', weight='semibold')

8. 箱形图隐藏的数据处理 Hidden data under boxplot

  • 添加分布散点图 boxplot with jitter
  • 使用小提琴图 use violinplot

箱形图总结了几个组的数值变量的分布。但是箱形图的问题不仅是丢失信息,这可能会结果有偏差。如果我们考虑下面的箱形图,很容易得出结论,'C’组的价值高于其他组。但是,我们无法看到每个组中点的基本分布是什么,也没有观察每个组的观察次数。所以我们需要对隐藏的数据进行处理

# libraries and data
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Dataset:
a = pd.DataFrame({ 'group' : np.repeat('A',500), 'value': np.random.normal(10, 5, 500) })
b = pd.DataFrame({ 'group' : np.repeat('B',500), 'value': np.random.normal(13, 1.2, 500) })
c = pd.DataFrame({ 'group' : np.repeat('B',500), 'value': np.random.normal(18, 1.2, 500) })
d = pd.DataFrame({ 'group' : np.repeat('C',20), 'value': np.random.normal(25, 4, 20) })
e = pd.DataFrame({ 'group' : np.repeat('D',100), 'value': np.random.uniform(12, size=100) })
df=a.append(b).append(c).append(d).append(e) # Usual boxplot
sns.boxplot(x='group', y='value', data=df);

# 添加分布散点图 boxplot with jitter
ax = sns.boxplot(x='group', y='value', data=df)
# 通过stripplot添加分布散点图,jitter设置数据间距
ax = sns.stripplot(x='group', y='value', data=df, color="orange", jitter=0.2, size=2.5)
plt.title("Boxplot with jitter", loc="left")
Text(0.0, 1.0, 'Boxplot with jitter')

# 使用小提琴图 use violinplot
sns.violinplot( x='group', y='value', data=df)
plt.title("Violin plot", loc="left")
Text(0.0, 1.0, 'Violin plot')

[seaborn] seaborn学习笔记1-箱形图Boxplot的更多相关文章

  1. GIS案例学习笔记-ArcGIS整图大图出图实例教程

    GIS案例学习笔记-ArcGIS整图大图出图实例教程 联系方式:谢老师,135-4855-4328,xiexiaokui#qq.com 1. 通过出图比例尺(1:2000),地图范围测算图纸大小. 图 ...

  2. UML学习笔记:类图

    UML学习笔记:类图 有些问题,不去解决,就永远都是问题! 类图 类图(Class Diagrame)是描述类.接口以及它们之间关系的图,用来显示系统中各个类的静态结构. 类图包含2种元素:类.接口, ...

  3. UML学习笔记:活动图

    UML学习笔记:活动图 活动图 活动图是UML中描述系统动态行为的图之一,用于展现参与行为的类的活动或动作.在UML里,活动图很类似于流程图,但是有一些区别: 活动图着重表现系统行为,描述对象活动的顺 ...

  4. [seaborn] seaborn学习笔记5-小提琴图VIOLINPLOT

    文章目录 5 小提琴图Violinplot 1. 基础小提琴图绘制 Basic violinplot 2. 小提琴图样式自定义 Custom seaborn violinplot 3. 小提琴图颜色自 ...

  5. [seaborn] seaborn学习笔记3-直方图Histogramplot

    文章目录 3 直方图Histogramplot 1. 基本直方图的绘制 Basic histogram 2. 数据分布与密度信息显示 Control rug and density on seabor ...

  6. [seaborn] seaborn学习笔记4-核密度图DENSITYPLOT

    文章目录 4 核密度图Densityplot 1. 基础核密度图绘制 Basic density plot 2. 核密度图的区间控制 Control bandwidth of density plot ...

  7. JS学习笔记--轮播图效果

    希望通过自己的学习收获哪怕收获一点点,进步一点点都是值得的,加油吧!!! 本章知识点:index this for if else 下边我分享下通过老师教的方式写的轮播图,基础知识实现: 1.css代 ...

  8. 吴恩达deepLearning.ai循环神经网络RNN学习笔记_看图就懂了!!!(理论篇)

    前言 目录: RNN提出的背景 - 一个问题 - 为什么不用标准神经网络 - RNN模型怎么解决这个问题 - RNN模型适用的数据特征 - RNN几种类型 RNN模型结构 - RNN block - ...

  9. C#学习笔记思维导图 一本书22张图

    阅读的书是<21天学通C#>博客中有下载 看看总结之后的模块 全部文件 初步展示 数据存储 继承模块 暂时就这些吧 全部思维导图22张打包下载

随机推荐

  1. Spring 深入——IoC 容器 01

    IoC容器的实现学习--01 目录 IoC容器的实现学习--01 简介 IoC 容器系列的设计与实现:BeanFactory 和 ApplicationContext BeanFactory load ...

  2. react.js 实现音乐播放、下一曲、以及删除歌曲(仅播放列表)

    import React, { Component } from 'react'; export default class Music extends Component {   construct ...

  3. 最近无聊搭建一个齐博X1的下载页面

    https://layui.wanxiangsucai.com/ 用layui官方镜像站的模版 改了个齐博X1的下载页面 https://x1.wanxiangsucai.com/ 哈哈哈!!! 还有 ...

  4. DQL语句

    DQL语句 DQL(Data QueryLanguage )数据查询语言,基本结构是由SELECT子句,FROM子句,WHERE子句组成的查询块. 一.DQL概述 1.1.什么是DQL DQL:数据查 ...

  5. JavaScript实现带省略号的分页

    1.实现功能 可以跳转上一页.下一页.数据过多省略号显示,点击省略号可以实现快速跳转. 纯js+html+css实现,引入js文件后再使用方法即可快速生成. 2.实现过程 2.1 html页面(ind ...

  6. ES6 学习笔记(八)基本类型Symbol

    1.前言 大家都知道,在ES5的时候JavaScript的基本类型有Number.String.Boolean.undefined.object.Null共6种,在es6中,新增了Symbol类型,用 ...

  7. 开源项目在线化 中文繁简体转换/敏感词/拼音/分词/汉字相似度/markdown 目录

    前言 以前在 github 上自己开源了一些项目.碍于技术与精力,大部分项目都是 java 实现的. 这对于非 java 开发者而言很不友好,对于不会编程的用户更加不友好. 为了让更多的人可以使用到这 ...

  8. C#中winform DataGridView常用修改点

    1.修改列名 一般情况下,从数据库里面读取的列名是英文或者拼音,但是,有时候显示需要中文,这样就需要修改列名了. dgv.Columns[0].HeaderCell.Value="编号&qu ...

  9. 常用Python库整理

    记录工作和学习中遇到和使用过的Python库. Target 四个Level 整理 Collect 学习 Learn 练习 Practice 掌握 Master 1. Python原生和功能增强 1. ...

  10. 嵌入式-C语言基础:字符串strlen和sizeof的区别

    strlen表示的实际的字符串长度,不会把字符串结束符'\0'计算进去,而sizeof则不是实际的字符串长度,它会把字符串的结束标识符'\0'也包含进去. #include<stdio.h> ...