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. 内存映射IO(MMIO)

    端口I/O 介绍: 一种I/O编址方式是端口映射I/O(port-mapped I/O), CPU使用专门的I/O指令对设备进行访问, 并把设备的地址称作端口号. 在执行其中的一条指令时,CPU使用地 ...

  2. Java I/O(3):NIO中的Buffer

    您好,我是湘王,这是我的博客园,欢迎您来,欢迎您再来- 之前在调用Channel的代码中,使用了一个名叫ByteBuffer类,它是Buffer的子类.这个叫Buffer的类是专门用来解决高速设备与低 ...

  3. 第一种方式:使用form表单将前端数据提交到servelt(将前端数据提交到servlet)

    第二种使用Ajax的形式将前台的数据传输到后台:https://blog.csdn.net/weixin_43304253/article/details/120335657 1.form表单 引入了 ...

  4. 中国制霸生成器「GitHub 热点速览 v.22.42」

    火遍推特的中国制霸生成器本周一开源就占据了两天的 GitHub Trending 榜,不知道你的足迹遍布了多少个省份呢?同样记录痕迹的 kanal 用了内存读写方式解决了 Rust 的消息处理问题,P ...

  5. MVC下拉框

    <select> @{ foreach (var item in 循环泛型) { <option value="@item.ID">@item.属性名< ...

  6. React动画实现方案之 Framer Motion,让你的页面“自己”动起来

    前言 相信很多前端同学都或多或少和动画打过交道.有的时候是产品想要的过度效果:有的时候是UI想要的酷炫动画.但是有没有人考虑过,是不是我们的页面上面的每一次变化,都可以像是自然而然的变化:是不是每一次 ...

  7. stm32h750移植lvgl

    之前没做过ui,只用过lcd画几条线写点字,如果按键.菜单什么的全用线画也太麻烦了,所以需要一个ui库. 听说lvgl用的人很多,就打算裸机移植一下用用.本文移植的lvgl版本是lvgl6.2,也移植 ...

  8. 5 why 分析法,一种用于归纳抽象出解决方案的好方法

    最近在看了<微信背后的产品观 - 张小龙手抄版>,其中有段话如下: 用户需求是零散的,解决方案是归纳抽象的过程 那如何归纳抽象呢?是否有一定的实践方法论呢?经过一轮探讨和学习,有这些答案: ...

  9. <四>构造函数初始化列表

    示例代码1 点击查看代码 class CDate{ public: CDate(int _year,int _month, int _day){ this->year=_year; this-& ...

  10. 【题解】P7860 [COCI2015-2016#2] ARTUR

    题面传送门 好题. 主要思路和另一位巨佬差不多,详细讲一下判断的部分. 解决思路: 首先考虑本题与拓扑排序有和关系.可以想到,某些棍子的先后移动顺序是有限制的.比如: 这里红色的必须比蓝色的先移动,因 ...