seaborn添加数据标签_常见Seaborn图的数据标签快速指南

seaborn添加数据标签

In the course of my data exploration adventures, I find myself looking at such plots (below), which is great for observing trend but it makes it difficult to make out where and what each data point is.

在进行数据探索的过程中,我发现自己正在查看此类图(如下),这对于观察趋势非常有用,但是很难确定每个数据点的位置和位置。

A line plot showing the total number of passengers yearly.
How many passengers are there in 1956?
1956年有多少乘客?

The purpose of this piece of writing is to provide a quick guide in labelling common data exploration seaborn graphs. All the code used can be found here.

本文的目的是提供一个快速指南,以标记常见的数据探索海洋图。 所有使用的代码都可以在这里找到。

建立 (Set-Up)

Seaborn’s flights dataset will be used for the purposes of demonstration.

Seaborn的航班数据集将用于演示。

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline# load dataset
flights = sns.load_dataset(‘flights’)
flights.head()
Dataframe showing the first 5 rows of the data in flights.
First 5 rows of the the data in flights
排期中数据的前5行

For increased ease and convenience in creating some plots, some additional data frames can be created.

为了增加创建某些绘图的便利性和便利性,可以创建一些其他数据框。

# set up flights by year dataframe
year_flights = flights.groupby(‘year’).sum().reset_index()
year_flights
Dataframe showing each year and the total number of flight passengers that year.
Total number of passengers for each year
每年的乘客总数
# set up average number of passengers by month dataframe
month_flights = flights.groupby(‘month’).agg({‘passengers’: ‘mean’}).reset_index()
month_flights
Dataframe showing each month of the year and the average number of flight passengers for that month.
Total number of passengers for each month
每个月的乘客总数

线图 (Line Plot)

Plotting a graph of passengers per year:

绘制每年的乘客图:

# plot line graph
sns.set(rc={‘figure.figsize’:(10,5)})
ax = sns.lineplot(x=’year’, y=’passengers’, data=year_flights, marker=’*’, color=’#965786')
ax.set(title=’Total Number of Passengers Yearly’)# label points on the plot
for x, y in zip(year_flights[‘year’], year_flights[‘passengers’]):
# the position of the data label relative to the data point can be adjusted by adding/subtracting a value from the x &/ y coordinates
plt.text(x = x, # x-coordinate position of data label
y = y-150, # y-coordinate position of data label, adjusted to be 150 below the data point
s = ‘{:.0f}’.format(y), # data label, formatted to ignore decimals
color = ‘purple’) # set colour of line
A line plot showing the total number of passengers yearly with data labels.
Line plot showing the total number of passengers yearly.
折线图显示了每年的乘客总数。

At times, it would be preferable for the data label to be more visible, which can be achieved by adding a background colour to the data labels:

有时,最好使数据标签更可见,这可以通过向数据标签添加背景色来实现:

# add set_backgroundcolor(‘color’) after plt.text(‘…’)
plt.text(x, y-150, ‘{:.0f}’.format(y), color=’white’).set_backgroundcolor(‘#965786’)
A line plot showing the total number of passengers yearly with data labels that have a background colour.
Line plot showing the total number of passengers yearly.
折线图显示了每年的乘客总数。

直方图 (Histogram)

Plotting a histogram of the frequency of passengers on each flight:

绘制每次航班上乘客频率的直方图:

# plot histogram 
ax = sns.distplot(flights[‘passengers’], color=’#9d94ba’, bins=10, kde=False)
ax.set(title=’Distribution of Passengers’)# label each bar in histogram
for p in ax.patches:
height = p.get_height() # get the height of each bar
# adding text to each bar
ax.text(x = p.get_x()+(p.get_width()/2), # x-coordinate position of data label, padded to be in the middle of the bar
y = height+0.2, # y-coordinate position of data label, padded 0.2 above bar
s = ‘{:.0f}’.format(height), # data label, formatted to ignore decimals
ha = ‘center’) # sets horizontal alignment (ha) to center
Histogram showing the frequency of passengers on each flight.
Histogram showing the number of passengers on each flight.
直方图显示每次航班上的乘客人数。

An additional information that might be beneficial to reflect in the graph as well is the mean line of the dataset:

可能也有益于在图中反映的其他信息是数据集的平均线:

# plot histogram 
# …# adding a vertical line for the average passengers per flight
plt.axvline(flights[‘passengers’].mean(), color=’purple’, label=’mean’)# adding data label to mean line
plt.text(x = flights[‘passengers’].mean()+3, # x-coordinate position of data label, adjusted to be 3 right of the data point
y = max([h.get_height() for h in ax.patches]), # y-coordinate position of data label, to take max height
s = ‘mean: {:.0f}’.format(flights[‘passengers’].mean()), # data label
color = ‘purple’) # colour of the vertical mean line# label each bar in histogram
# …
Histogram showing the frequency of passengers on each flight with a vertical line indicating the mean.
Histogram showing the number of passengers on each flight and a line indicating the mean.
直方图显示每次航班上的乘客人数,线表示平均值。

条形图 (Bar Plot)

Vertical Bar Plot

垂直条形图

Plotting the total number of passengers for each year:

绘制每年的乘客总数:

# plot vertical barplot
sns.set(rc={‘figure.figsize’:(10,5)})
ax = sns.barplot(x=’year’, y=’passengers’, data=year_flights)
ax.set(title=’Total Number of Passengers Yearly’) # title barplot# label each bar in barplot
for p in ax.patches:
# get the height of each bar
height = p.get_height()
# adding text to each bar
ax.text(x = p.get_x()+(p.get_width()/2), # x-coordinate position of data label, padded to be in the middle of the bar
y = height+100, # y-coordinate position of data label, padded 100 above bar
s = ‘{:.0f}’.format(height), # data label, formatted to ignore decimals
ha = ‘center’) # sets horizontal alignment (ha) to center
Bar Plot with vertical bars showing the total number of passengers yearly.
Bar plot with vertical bars showing the total number of passengers yearly
竖线条形图,显示每年的乘客总数

Horizontal Bar Plot

水平条形图

Plotting the average number of passengers on flights each month:

绘制每月航班的平均乘客数:

# plot horizontal barplot
sns.set(rc={‘figure.figsize’:(10,5)})
ax = sns.barplot(x=’passengers’, y=’month’, data=month_flights, orient=’h’)
ax.set(title=’Average Number of Flight Passengers Monthly’) # title barplot# label each bar in barplot
for p in ax.patches:
height = p.get_height() # height of each horizontal bar is the same
width = p.get_width() # width (average number of passengers)
# adding text to each bar
ax.text(x = width+3, # x-coordinate position of data label, padded 3 to right of bar
y = p.get_y()+(height/2), # # y-coordinate position of data label, padded to be in the middle of the bar
s = ‘{:.0f}’.format(width), # data label, formatted to ignore decimals
va = ‘center’) # sets vertical alignment (va) to center
Bar plot with horizontal bars showing the average number of passengers for each month.
Bar plot with horizontal bars showing the average number of passengers for each month
带有水平条的条形图,显示每个月的平均乘客人数

使用注意事项 (Notes on Usage)

It might be beneficial to add data labels to some plots (especially bar plots), it would be good to experiment and test out different configurations (such as using labels only for certain meaningful points, instead of labelling everything) and not overdo the labelling, especially if there are many points. A clean and informative graph is usually more preferable than a cluttered one.

将数据标签添加到某些图(尤其是条形图)可能是有益的,尝试并测试不同的配置(例如仅对某些有意义的点使用标签,而不是对所有内容进行标签),并且不要过度标注,特别是如果有很多要点的话。 通常,干净整洁的图表比混乱的图表更可取。

# only labelling some points on graph# plot line graph
sns.set(rc={‘figure.figsize’:(10,5)})
ax = sns.lineplot(x=’year’, y=’passengers’, data=year_flights, marker=’*’, color=’#965786')# title the plot
ax.set(title=’Total Number of Passengers Yearly’)mean = year_flights[‘passengers’].mean()# label points on the plot only if they are higher than the mean
for x, y in zip(year_flights[‘year’], year_flights[‘passengers’]):
if y > mean:
plt.text(x = x, # x-coordinate position of data label
y = y-150, # y-coordinate position of data label, adjusted to be 150 below the data point
s = ‘{:.0f}’.format(y), # data label, formatted to ignore decimals
color = ‘purple’) # set colour of line
A line plot showing the total number of passengers yearly.
Line plot showing the total number of passengers yearly.
折线图显示了每年的乘客总数。

翻译自: https://medium.com/swlh/quick-guide-to-labelling-data-for-common-seaborn-plots-736e10bf14a9

seaborn添加数据标签

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/389210.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

使用python pandas dataframe学习数据分析

⚠️ Note — This post is a part of Learning data analysis with python series. If you haven’t read the first post, some of the content won’t make sense. Check it out here.Note️ 注意 -这篇文章是使用python系列学习数据分析的一部分。 如果您还没有阅读第一篇文…

实现TcpIp简单传送

private void timer1_Tick(object sender, EventArgs e) { IPAddress ipstr IPAddress.Parse("192.168.0.106"); TcpListener serverListener new TcpListener(ipstr,13);//创建TcpListener对象实例 ser…

SQLServer之函数简介

用户定义函数定义 与编程语言中的函数类似,SQL Server 用户定义函数是接受参数、执行操作(例如复杂计算)并将操作结果以值的形式返回的例程。 返回值可以是单个标量值或结果集。 用户定义函数准则 在函数中,将会区别处理导致语句被…

无向图g的邻接矩阵一定是_矩阵是图

无向图g的邻接矩阵一定是To study structure,tear away all flesh soonly the bone shows.要研究结构,请尽快撕掉骨头上所有的肉。 Linear algebra. Graph theory. If you are a data scientist, you have encountered both of these fields in your study or work …

移动pc常用Meta标签

移动常用 <meta charset"UTF-8"><title>{$configInfos[store_title]}</title><meta content"widthdevice-width,minimum-scale1.0,maximum-scale1.0,shrink-to-fitno,user-scalableno,minimal-ui" name"viewport"><m…

前端绘制绘制图表_绘制我的文学风景

前端绘制绘制图表Back when I was a kid, I used to read A LOT of books. Then, over the last couple of years, movies and TV series somehow stole the thunder, and with it, my attention. I did read a few odd books here and there, but not with the same ferocity …

Rapi

本页内容 ●引言●SMARTPHONE SDK API 库●管理设备中的目录文件●取系统信息●远程操作电话和短信功能 Windows Mobile日益成熟&#xff0c;开发者队伍也越来越壮大。作为一个10年的计算机热爱者和程序员&#xff0c;我也经受不住新技术的诱惑&#xff0c;倒腾起Mobile这个玩具…

android 字符串特殊字符转义

XML转义字符 以下为XML标志符的数字和字符串转义符 " ( 或 &quot;) ( 或 &apos;) & ( 或 &amp;) lt(<) (< 或 <) gt(>) (> 或 >) 如题&#xff1a; 比如&#xff1a;在string.xml中定义如下一个字符串&#xff0c;…

如何描绘一个vue的项目_描绘了一个被忽视的幽默来源

如何描绘一个vue的项目Source)来源 ) Data visualization is a great way to celebrate our favorite pieces of art as well as reveal connections and ideas that were previously invisible. More importantly, it’s a fun way to connect things we love — visualizing …

数据存储加密和传输加密_将时间存储网络应用于加密预测

数据存储加密和传输加密I’m not going to string you along until the end, dear reader, and say “Didn’t achieve anything groundbreaking but thanks for reading ;)”.亲爱的读者&#xff0c;我不会一直待到最后&#xff0c;然后说&#xff1a; “没有取得任何开创性的…

熊猫分发_熊猫新手:第一部分

熊猫分发For those just starting out in data science, the Python programming language is a pre-requisite to learning data science so if you aren’t familiar with Python go make yourself familiar and then come back here to start on Pandas.对于刚接触数据科学的…

多线程 进度条 C# .net

前言  在我们应用程序开发过程中&#xff0c;经常会遇到一些问题&#xff0c;需要使用多线程技术来加以解决。本文就是通过几个示例程序给大家讲解一下多线程相关的一些主要问题。 执行长任务操作  许多种类的应用程序都需要长时间操作&#xff0c;比如&#xff1a;执行一…

window 10 多版本激活工具

window 10 通用版激活工具 云盘地址&#xff1a;https://pan.baidu.com/s/1bo3L4Kn 激活工具网站&#xff1a;http://www.tudoupe.com/win10/win10jihuo/2017/0516/6823.html 转载于:https://www.cnblogs.com/ipyanthony/p/9288007.html

android 动画总结笔记 一

终于有时间可以详细去了解一下 android动画&#xff0c;先从android动画基础着手。在android 3.0之前android动画api主要是android.view.Animation包下的内容&#xff0c;来先看看这个包里面主要的类![Animation成员](https://img-blog.csdn.net/20150709115201928 "Anima…

《Linux内核原理与分析》第六周作业

课本&#xff1a;第五章 系统调用的三层机制&#xff08;下&#xff09; 中断向量0x80和system_call中断服务程序入口的关系 0x80对应着system_call中断服务程序入口&#xff0c;在start_kernel函数中调用了trap_init函数&#xff0c;trap_init函数中调用了set_system_trap_gat…

使用C#调用外部Ping命令获取网络连接情况

使用C#调用外部Ping命令获取网络连接情况 以前在玩Windows 98的时候&#xff0c;几台电脑连起来&#xff0c;需要测试网络连接是否正常&#xff0c;经常用的一个命令就是Ping.exe。感觉相当实用。 现在 .net为我们提供了强大的功能来调用外部工具&#xff0c;并通过重定向输…

Codeforces Round 493

心情不好&#xff0c;被遣散回学校 &#xff0c;心态不好 &#xff0c;为什么会累&#xff0c;一直微笑就好了 #include<bits/stdc.h> using namespace std; int main() {freopen("in","r",stdin);\freopen("out","w",stdout);i…

android动画笔记二

从android3.0&#xff0c;系统提供了一个新的动画&#xff0d;property animation, 为什么系统会提供这样一个全新的动画包呢&#xff0c;先来看看之前的补间动画都有什么缺陷吧1、传统的补间动画都是固定的编码&#xff0c;功能是固定的&#xff0c;扩展难度大。比如传统动画只…

回归分析检验_回归分析

回归分析检验Regression analysis is a reliable method in statistics to determine whether a certain variable is influenced by certain other(s). The great thing about regression is also that there could be multiple variables influencing the variable of intere…