[seaborn] seaborn学习笔记1-箱形图Boxplot
文章目录
1 箱形图Boxplot
(代码下载)
Boxplot可能是最常见的图形类型之一。它能够很好表示数据中的分布规律。箱型图方框的末尾显示了上下四分位数。极线显示最高和最低值,不包括异常值。seaborn中用boxplot函数制作箱形图。该章节主要内容有:
- 基础箱形图绘制 Basic boxplot and input format
- 自定义外观 Custom boxplot appearance
- 箱型图的颜色设置 Control colors of boxplot
- 分组箱图 Grouped Boxplot
- 箱图的顺序设置 Control order of boxplot
- 添加散点分布 Add jitter over boxplot
- 显示各类的样本数 Show number of observation on boxplot
- 箱形图隐藏的数据处理 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的更多相关文章
- GIS案例学习笔记-ArcGIS整图大图出图实例教程
GIS案例学习笔记-ArcGIS整图大图出图实例教程 联系方式:谢老师,135-4855-4328,xiexiaokui#qq.com 1. 通过出图比例尺(1:2000),地图范围测算图纸大小. 图 ...
- UML学习笔记:类图
UML学习笔记:类图 有些问题,不去解决,就永远都是问题! 类图 类图(Class Diagrame)是描述类.接口以及它们之间关系的图,用来显示系统中各个类的静态结构. 类图包含2种元素:类.接口, ...
- UML学习笔记:活动图
UML学习笔记:活动图 活动图 活动图是UML中描述系统动态行为的图之一,用于展现参与行为的类的活动或动作.在UML里,活动图很类似于流程图,但是有一些区别: 活动图着重表现系统行为,描述对象活动的顺 ...
- [seaborn] seaborn学习笔记5-小提琴图VIOLINPLOT
文章目录 5 小提琴图Violinplot 1. 基础小提琴图绘制 Basic violinplot 2. 小提琴图样式自定义 Custom seaborn violinplot 3. 小提琴图颜色自 ...
- [seaborn] seaborn学习笔记3-直方图Histogramplot
文章目录 3 直方图Histogramplot 1. 基本直方图的绘制 Basic histogram 2. 数据分布与密度信息显示 Control rug and density on seabor ...
- [seaborn] seaborn学习笔记4-核密度图DENSITYPLOT
文章目录 4 核密度图Densityplot 1. 基础核密度图绘制 Basic density plot 2. 核密度图的区间控制 Control bandwidth of density plot ...
- JS学习笔记--轮播图效果
希望通过自己的学习收获哪怕收获一点点,进步一点点都是值得的,加油吧!!! 本章知识点:index this for if else 下边我分享下通过老师教的方式写的轮播图,基础知识实现: 1.css代 ...
- 吴恩达deepLearning.ai循环神经网络RNN学习笔记_看图就懂了!!!(理论篇)
前言 目录: RNN提出的背景 - 一个问题 - 为什么不用标准神经网络 - RNN模型怎么解决这个问题 - RNN模型适用的数据特征 - RNN几种类型 RNN模型结构 - RNN block - ...
- C#学习笔记思维导图 一本书22张图
阅读的书是<21天学通C#>博客中有下载 看看总结之后的模块 全部文件 初步展示 数据存储 继承模块 暂时就这些吧 全部思维导图22张打包下载
随机推荐
- C# 基础 之:Task 用法
参考来源:https://www.cnblogs.com/zhaoshujie/p/11082753.html 他介绍的可以说是非常详细,附带Demo例子讲解 1.入门 Task看起来像一个Threa ...
- 2022-08-05-欢迎使用_Typecho
layout: post cid: 1 title: 欢迎使用 Typecho slug: start date: 2022/08/05 14:21:51 updated: 2022/08/05 14 ...
- IDEA清空控制台以及Java中运行cmd命令实现清屏操作
IDEA中清空控制台方法 在网上有看到各种的实现方法,比如: Runtime.getRuntime().exec("cls"); 或者: public static void cl ...
- C语言经典编程100题
程序1] 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月 后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? 1.程序分析: 兔子的规律为数列1,1 ...
- C#中下载项目中的文件
1.将需要下载的文档添加到项目的文件夹中 2.接口部分 public IActionResult DownLoad() { var filePath = Directory.GetCurrentDir ...
- Spring事务传播行为实战
一.什么是事务传播行为? 事务传播行为(propagation behavior)指的就是当一个事务方法被另一个事务方法调用时,这个事务方法应该如何运行. 例如:methodA方法调用methodB方 ...
- GIT入门与Gitee的使用
一:Git是什么? Git是目前世界上最先进的分布式版本控制系统. 工作原理 / 流程: Workspace:工作区Index / Stage:暂存区Repository:仓库区(或本地仓库)Remo ...
- Linux系统部署Jenkins
搭建Jenkins,准备搞一个定时任务来自动部署服务.做个记录. 问题写在前头:①建议使用最新版的Jenkins版本,jdk版本要跟Jenkins版本对应(有要求):②最好使用war包部署Jenkin ...
- freeswitch的mod_curl模块
概述 有时候,我们需要在呼叫的过程中,或过程后调用web api接口. freeswitch的mod_curl模块可以很方便的实现web api的接口调用. mod_curl模块默认不安装,需要进入模 ...
- 【笔记】P1606 [USACO07FEB]Lilypad Pond G 及相关
题目传送门 建图 首先,根据题目,可以判断出这是一道最短路计数问题. 但是要跑最短路,首先要用他给的信息建图,这是非常关键的一步. 根据题意,我们可以想出以下建图规则: 起点或是一个空白处可以花费 \ ...