seaborn分布数据可视化:直方图|密度图|散点图

系统自带的数据表格(存放在github上https://github.com/mwaskom/seaborn-data),使用时通过sns.load_dataset('表名称')即可,结果为一个DataFrame。

print(sns.get_dataset_names())   #获取所有数据表名称
# ['anscombe', 'attention', 'brain_networks', 'car_crashes', 'diamonds', 'dots', 'exercise', 'flights', 
# 'fmri', 'gammas', 'iris', 'mpg', 'planets', 'tips', 'titanic']
tips = sns.load_dataset('tips')  #导入小费tips数据表,返回一个DataFrame
tips.head()

 

一、直方图distplot()

distplot(a, bins=None, hist=True, kde=True, rug=False, fit=None,hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None,color=None, vertical=False,       

             norm_hist=False, axlabel=None,label=None, ax=None)

  • a 数据源
  • bins 箱数
  • hist、kde、rug 是否显示箱数、密度曲线、数据分布,默认显示箱数和密度曲线不显示数据分析
  • {hist,kde,rug}_kws 通过字典形式设置箱数、密度曲线、数据分布的各个特征
  • norm_hist 直方图的高度是否显示密度,默认显示计数,如果kde设置为True高度也会显示为密度
  • color 颜色
  • vertical 是否在y轴上显示图标,默认为False即在x轴显示,即竖直显示
  • axlabel 坐标轴标签
  • label 直方图标签
fig = plt.figure(figsize=(12,5))
ax1 = plt.subplot(121)
rs = np.random.RandomState(10)  # 设定随机数种子
s = pd.Series(rs.randn(100) * 100)
sns.distplot(s,bins = 10,hist = True,kde = True,rug = True,norm_hist=False,color = 'y',label = 'distplot',axlabel = 'x')
plt.legend()ax1 = plt.subplot(122)
sns.distplot(s,rug = True, hist_kws={"histtype": "step", "linewidth": 1,"alpha": 1, "color": "g"},  # 设置箱子的风格、线宽、透明度、颜色,风格包括:'bar', 'barstacked', 'step', 'stepfilled'        kde_kws={"color": "r", "linewidth": 1, "label": "KDE",'linestyle':'--'},   # 设置密度曲线颜色,线宽,标注、线形rug_kws = {'color':'r'} )  # 设置数据频率分布颜色

二、密度图

密度曲线kdeplot(data, data2=None, shade=False, vertical=False, kernel="gau",bw="scott", gridsize=100, cut=3, clip=None,                     

    legend=True,cumulative=False,shade_lowest=True,cbar=False, cbar_ax=None,cbar_kws=None, ax=None, **kwargs)

  • shade 是否填充与坐标轴之间的
  • bw 取值'scott' 、'silverman'或一个数值标量,控制拟合的程度,类似直方图的箱数,设置的数量越大越平滑,越小越容易过度拟合
  • shade_lowest 主要是对两个变量分析时起作用,是否显示最外侧填充颜色,默认显示
  • cbar 是否显示颜色图例
  • n_levels 主要对两个变量分析起作用,数据线的个数

数据分布rugplot(a, height=.05, axis="x", ax=None, **kwargs)

  • height 分布线高度
  • axis {'x','y'},在x轴还是y轴显示数据分布

1.单个样本数据分布密度图 

sns.kdeplot(s,shade = False, color = 'r',vertical = False)# 是否填充、设置颜色、是否水平
sns.kdeplot(s,bw=0.2, label="bw: 0.2",linestyle = '-',linewidth = 1.2,alpha = 0.5)
sns.kdeplot(s,bw=2, label="bw: 2",linestyle = '-',linewidth = 1.2,alpha = 0.5,shade=True)
sns.rugplot(s,height = 0.1,color = 'k',alpha = 0.5)  #数据分布

2.两个样本数据分布密度图

两个维度数据生成曲线密度图,以颜色作为密度衰减显示。

rs = np.random.RandomState(2)  # 设定随机数种子
df = pd.DataFrame(rs.randn(100,2),columns = ['A','B'])
sns.kdeplot(df['A'],df['B'],shade = True,cbar = True,cmap = 'Reds',shade_lowest=True, n_levels = 8)# 曲线个数(如果非常多,则会越平滑) 
plt.grid(linestyle = '--')
plt.scatter(df['A'], df['B'], s=5, alpha = 0.5, color = 'k') #散点
sns.rugplot(df['A'], color="g", axis='x',alpha = 0.5) #x轴数据分布
sns.rugplot(df['B'], color="r", axis='y',alpha = 0.5) #y轴数据分布

rs1 = np.random.RandomState(2)  
rs2 = np.random.RandomState(5)  
df1 = pd.DataFrame(rs1.randn(100,2)+2,columns = ['A','B'])
df2 = pd.DataFrame(rs2.randn(100,2)-2,columns = ['A','B'])
sns.set_style('darkgrid')
sns.set_context('talk')
sns.kdeplot(df1['A'],df1['B'],cmap = 'Greens',shade = True,shade_lowest=False)
sns.kdeplot(df2['A'],df2['B'],cmap = 'Blues', shade = True,shade_lowest=False)

三、散点图

jointplot() / JointGrid() / pairplot() /pairgrid()

1.jointplot()综合散点图

rs = np.random.RandomState(2)  
df = pd.DataFrame(rs.randn(200,2),columns = ['A','B'])sns.jointplot(x=df['A'], y=df['B'],  # 设置x轴和y轴,显示columns名称data=df,   # 设置数据color = 'k',   # 设置颜色s = 50, edgecolor="w",linewidth=1,  # 设置散点大小、边缘线颜色及宽度(只针对scatter)kind = 'scatter',   # 设置类型:“scatter”、“reg”、“resid”、“kde”、“hex”space = 0.1,  # 设置散点图和上方、右侧直方图图的间距size = 6,   # 图表大小(自动调整为正方形)ratio = 3,  # 散点图与直方图高度比,整型marginal_kws=dict(bins=15, rug=True,color='green')  # 设置直方图箱数以及是否显示rug)  

当kind分别设置为其他4种“reg”、“resid”、“kde”、“hex”时,图表如下。

sns.jointplot(x=df['A'], y=df['B'],data=df,kind='reg',size=5)  #
sns.jointplot(x=df['A'], y=df['B'],data=df,kind='resid',size=5) #
sns.jointplot(x=df['A'], y=df['B'],data=df,kind='kde',size=5) #
sns.jointplot(x=df['A'], y=df['B'],data=df,kind='hex',size=5) #蜂窝图

 

在密度图中添加散点图,先通过sns.jointplot()创建密度图并赋值给变量,再通过变量.plot_joint()在密度图中添加散点图。

rs = np.random.RandomState(15)
df = pd.DataFrame(rs.randn(300,2),columns = ['A','B'])
g = sns.jointplot(x=df['A'], y=df['B'],data = df, kind="kde", color="pink",shade_lowest=False) #密度图,并赋值给一个变量
g.plot_joint(plt.scatter,c="w", s=30, linewidth=1, marker="+")  #在密度图中添加散点图

2.拆分综合散点图JointGrid() 

上述综合散点图可分为上、右、中间三部分,设置属性时对这三个参数都生效,JointGrid()可将这三部分拆开分别设置属性。

①拆分为中间+上&右 两部分设置

# plot_joint() + plot_marginals()
g = sns.JointGrid(x="total_bill", y="tip", data=tips)# 创建一个绘图区域,并设置好x、y对应数据
g = g.plot_joint(plt.scatter,color="g", s=40, edgecolor="white")   # 中间区域通过g.plot_joint绘制散点图
plt.grid('--')g.plot_marginals(sns.distplot, kde=True, color="y")     #

h = sns.JointGrid(x="total_bill", y="tip", data=tips)# 创建一个绘图区域,并设置好x、y对应数据
h = h.plot_joint(sns.kdeplot,cmap = 'Reds_r')   # 中间区域通过g.plot_joint绘制散点图
plt.grid('--')
h.plot_marginals(sns.kdeplot, color="b") 

 

②拆分为中间+上+右三个部分分别设置

# plot_joint() + ax_marg_x.hist() + ax_marg_y.hist()

sns.set_style("white")# 设置风格
tips = sns.load_dataset("tips") # 导入系统的小费数据
print(tips.head())g = sns.JointGrid(x="total_bill", y="tip", data=tips)# 创建绘图区域,设置好x、y对应数据

g.plot_joint(plt.scatter, color ='y', edgecolor = 'white')  # 设置内部散点图scatter
g.ax_marg_x.hist(tips["total_bill"], color="b", alpha=.6,bins=np.arange(0, 60, 3))  # 设置x轴直方图,注意bins是数组
g.ax_marg_y.hist(tips["tip"], color="r", alpha=.6, orientation="horizontal", bins=np.arange(0, 12, 1)) # 设置y轴直方图,需要orientation参数from scipy import stats
g.annotate(stats.pearsonr)  # 设置标注,可以为pearsonr,spearmanr

plt.grid(linestyle = '--')

3.pairplot()矩阵散点图

矩阵散点图类似pandas的pd.plotting.scatter_matrix(...),将数据从多个维度进行两两对比。

对角线默认显示密度图,非对角线默认显示散点图。

sns.set_style("white")
iris = sns.load_dataset("iris")
print(iris.head())
sns.pairplot(iris,kind = 'scatter',  # 散点图/回归分布图 {‘scatter’, ‘reg’}  diag_kind="hist",  # 对角线处直方图/密度图 {‘hist’, ‘kde’}hue="species",   # 按照某一字段进行分类palette="husl",  # 设置调色板markers=["o", "s", "D"],  # 设置不同系列的点样式(个数与hue分类的个数一致)height = 1.5,   # 图表大小)

 

对原数据的局部变量进行分析,可添加参数vars

sns.pairplot(iris,vars=["sepal_width", "sepal_length"], kind = 'reg', diag_kind="kde", hue="species", palette="husl")

 

plot_kws()和diag_kws()可分别设置对角线和非对角线的显示

sns.pairplot(iris, vars=["sepal_length", "petal_length"],diag_kind="kde", markers="+",plot_kws=dict(s=50, edgecolor="b", linewidth=1),# 设置非对角线点样式diag_kws=dict(shade=True,color='r',linewidth=1)# 设置对角线密度图样式)

4..拆分综合散点图JointGrid() 

类似JointGrid()的功能,将矩阵散点图拆分为对角线和非对角线图表分别设置显示属性。

①拆分为对角线和非对角线

# map_diag() + map_offdiag()

g = sns.PairGrid(iris,hue="species",palette = 'hls',vars=["sepal_width", "sepal_length"])
g.map_diag(plt.hist, # 对角线图表,plt.hist/sns.kdeplothisttype = 'barstacked',   # 可选:'bar', 'barstacked', 'step', 'stepfilled'linewidth = 1, edgecolor = 'gray')           
g.map_offdiag(plt.scatter, # f非对角线其他图表,plt.scatter/plt.bar...edgecolor="yellow", s=20, linewidth = 1,   # 设置点颜色、大小、描边宽度)   

 

    

 

②拆分为对角线+对角线上+对角线下 3部分设置

# map_diag() + map_lower() + map_upper()
g = sns.PairGrid(iris)
g.map_diag(sns.kdeplot, lw=1.5,color='y',alpha=0.5)   # 设置对角线图表
g.map_upper(plt.scatter, color = 'r',s=8)     # 设置对角线上端图表显示为散点图
g.map_lower(sns.kdeplot,cmap='Blues_r') # 设置对角线下端图表显示为多密度分布图

       

 

转载于:https://www.cnblogs.com/Forever77/p/11399523.html

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

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

相关文章

如何成为一个优秀的程序员_如何成为一名优秀的程序员

如何成为一个优秀的程序员by Amy M Haddad通过艾米M哈达德(Amy M Haddad) 如何成为一名优秀的程序员 (How to be a great programmer) What sets apart the really great programmers?是什么使真正出色的程序员与众不同? As we all know, great programmers buil…

pymc3使用_使用PyMC3了解飞机事故趋势

pymc3使用Visually exploring historic airline accidents, applying frequentist interpretations and validating changing trends with PyMC3.使用PyMC3直观地浏览历史性航空事故,应用常识性解释并验证变化趋势。 前言 (Preface) On the 7th of August this yea…

视频监控业务上云方案解析

摘要:阿里云针对安防监控服务在传统IT架构下面临的上述问题,基于阿里云存储服务,提供视频监控解决方案。从2015年推出视频监控存储与播放解决方案以来,帮助大量的视频监控企业解决了上云的过程中遇到的问题,针对不同的…

leetcode 341. 扁平化嵌套列表迭代器(dfs)

给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。 示例 1: 输入: [[1,1],2,[1,1]] 输出: [1,1,2,1,1] 解释: 通过重复…

爬虫结果数据完整性校验

数据完整性分为三个方面: 1、域完整性(列) 限制输入数据的类型,及范围,或者格式,如性别字段必须是“男”或者“女”,不允许其他数据插入,成绩字段只能是0-100的整型数据,…

go map数据结构

map数据结构 key-value的数据结构,又叫字典或关联数组 声明:var map1 map[keytype]valuetype var a map[string]string var a map[string]int var a map[int]string var a map[string]map[string]string备注:声明是不会分配内存的&#xff0c…

吴恩达神经网络1-2-2_图神经网络进行药物发现-第2部分

吴恩达神经网络1-2-2预测毒性 (Predicting Toxicity) 相关资料 (Related Material) Jupyter Notebook for the article Jupyter Notebook的文章 Drug Discovery with Graph Neural Networks — part 1 图神经网络进行药物发现-第1部分 Introduction to Cheminformatics 化学信息…

android初学者_适用于初学者的Android广播接收器

android初学者Let’s say you have an application that depends on a steady internet connection. You want your application to get notified when the internet connection changes. How do you do that?假设您有一个依赖稳定互联网连接的应用程序。 您希望您的应用程序在…

Android热修复之 - 阿里开源的热补丁

1.1 基本介绍     我们先去github上面了解它https://github.com/alibaba/AndFix 这里就有一个概念那就AndFix.apatch补丁用来修复方法,接下来我们看看到底是怎么实现的。1.2 生成apatch包      假如我们收到了用户上传的崩溃信息,我们改完需要修复…

leetcode 456. 132 模式(单调栈)

给你一个整数数组 nums &#xff0c;数组中共有 n 个整数。132 模式的子序列 由三个整数 nums[i]、nums[j] 和 nums[k] 组成&#xff0c;并同时满足&#xff1a;i < j < k 和 nums[i] < nums[k] < nums[j] 。 如果 nums 中存在 132 模式的子序列 &#xff0c;返回…

seaborn分类数据可视:散点图|箱型图|小提琴图|lv图|柱状图|折线图

一、散点图stripplot( ) 与swarmplot&#xff08;&#xff09; 1.分类散点图stripplot( ) 用法stripplot(xNone, yNone, hueNone, dataNone, orderNone, hue_orderNone,jitterTrue, dodgeFalse, orientNone, colorNone, paletteNone,size5, edgecolor"gray", linewi…

数据图表可视化_数据可视化十大最有用的图表

数据图表可视化分析师每天使用的最佳数据可视化图表列表。 (List of best data visualization charts that Analysts use on a daily basis.) Presenting information or data in a visual format is one of the most effective ways. Researchers have proved that the human …

javascript实现自动添加文本框功能

转自&#xff1a;http://www.cnblogs.com/damonlan/archive/2011/08/03/2126046.html 昨天&#xff0c;我们公司的网络小组决定为公司做一个内部的网站&#xff0c;主要是为员工比如发布公告啊、填写相应信息、投诉、问题等等需求。我那同事给了我以下需求&#xff1a; 1.点击一…

从Mysql slave system lock延迟说开去

本文主要分析 sql thread中system lock出现的原因&#xff0c;但是笔者并明没有系统的学习过master-slave的代码&#xff0c;这也是2018年的一个目标&#xff0c;2018年我都排满了&#xff0c;悲剧。所以如果有错误请指出&#xff0c;也作为一个笔记用于后期学习。同时也给出笔…

传智播客全栈_播客:从家庭学生到自学成才的全栈开发人员

传智播客全栈In this weeks episode of the freeCodeCamp podcast, Abbey chats with Madison Kanna, a full-stack developer who works remotely for Mediavine. Madison describes how homeschooling affected her future learning style, how she tackles imposter syndrom…

leetcode 82. 删除排序链表中的重复元素 II(map)

解题思路 map记录数字出现的次数&#xff0c;出现次数大于1的数字从链表中移除 代码 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val val; }* ListNode(…

python 列表、字典多排序问题

版权声明&#xff1a;本文为博主原创文章&#xff0c;遵循 CC 4.0 by-sa 版权协议&#xff0c;转载请附上原文出处链接和本声明。本文链接&#xff1a;https://blog.csdn.net/justin051/article/details/84289189Python使用sorted函数来排序&#xff1a; l [2,1,3,5,7,3]print…

接facebook广告_Facebook广告分析

接facebook广告Is our company’s Facebook advertising even worth the effort?我们公司的Facebook广告是否值得努力&#xff1f; 题&#xff1a; (QUESTION:) A company would like to know if their advertising is effective. Before you start, yes…. Facebook does ha…

如何创建自定义进度栏

Originally published on www.florin-pop.com最初发布在www.florin-pop.com The theme for week #14 of the Weekly Coding Challenge is: 每周编码挑战第14周的主题是&#xff1a; 进度条 (Progress Bar) A progress bar is used to show how far a user action is still in…

基于SpringBoot的CodeGenerator

title: 基于SpringBoot的CodeGenerator tags: SpringBootMybatis生成器PageHelper categories: springboot date: 2017-11-21 15:13:33背景 目前组织上对于一个基础的crud的框架需求较多 因此选择了SpringBoot作为基础选型。 Spring Boot是由Pivotal团队提供的全新框架&#xf…