python可视化进阶---seaborn1.4 分布数据可视化 - 散点图 jointplot() / pairplot()

简介: 一、分布数据可视化 - 散点图jointplot() / pairplot()加载模块

一、分布数据可视化 - 散点图

jointplot() / pairplot()

加载模块

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats as sci

1、综合散点图 - jointplot()

1.1散点图 + 分布图

示例1:

#创建数据
rs = np.random.RandomState(2)
df = pd.DataFrame(rs.randn(200,2), columns = ['A','B'])
sns.jointplot(x=df['A'], y=df['B'], #设置xy轴,显示columns名称
              data = df,  #设置数据
              color = 'b', #设置颜色
              s = 50, edgecolor = 'w', linewidth = 1,#设置散点大小、边缘颜色及宽度(只针对scatter)
              stat_func=sci.pearsonr,
              kind = 'scatter',#设置类型:'scatter','reg','resid','kde','hex'
              #stat_func=<function pearsonr>,
              space = 0.1, #设置散点图和布局图的间距
              size = 8, #图表大小(自动调整为正方形))
              ratio = 5, #散点图与布局图高度比,整型
              marginal_kws = dict(bins=15, rug =True), #设置柱状图箱数,是否设置rug
              )

20180911141851160.png

图1.散点分布图

注意:如果不显示r值(pearsonr),可以在参数中添加stat_func=sci.pearsonr,有就不用添加了

示例2:六边形图

sns.jointplot(x=df['A'], y=df['B'], #设置xy轴,显示columns名称
              data = df,  #设置数据
              color = 'b', #设置颜色
              #s = 50, edgecolor = 'w', linewidth = 1,#设置散点大小、边缘颜色及宽度(只针对scatter)
              stat_func=sci.pearsonr,
              kind = 'hex',#设置类型:'scatter','reg','resid','kde','hex'
              space = 0.1, #设置散点图和布局图的间距
              size = 8, #图表大小(自动调整为正方形))
              ratio = 5, #散点图与布局图高度比,整型
             # marginal_kws = dict(bins=15, rug =True) #设置柱状图箱数,是否设置rug
              )

20180911142105665.png

六边形图也可以叫做蜂巢图

示例3:六边形图

#创建数据
df = pd.DataFrame(rs.randn(500,2), columns = ['A', 'B'])
with sns.axes_style('white'):
    sns.jointplot(x=df['A'], y=df['B'], data = df, kind = 'hex',
                  color = 'k',stat_func=sci.pearsonr,
                  marginal_kws = dict(bins = 20))

201809111423143.png

示例4: 密度图

#创建数据
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 = 'k', stat_func= sci.pearsonr,
                  shade_lowest = False)
#添加散点图
g.plot_joint(plt.scatter, c = 'w', s = 30, linewidth = 1, marker='+')

2018091114243770.png

1.2可拆分绘制的散点图

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

示例1:拆分图

#设置风格
sns.set_style('white')
#导入数据
tips = sns.load_dataset('tips')
print(tips.head())
#创建一个绘图表格区域,设置好x,y对应数据
g = sns.JointGrid(x = 'total_bill', y = 'tip', data = tips)
g.plot_joint(plt.scatter, color = 'm', 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)) #设置x轴直方图,注意需要orientation参数
from scipy import stats
g.annotate(stats.pearsonr)
#设置标注,可以为pearsonar, spearmanr
plt.grid(linestyle = '--')

20180911142712355.png

示例2:两个条形图在一个函数里进行设置

#创建一个绘图表格区域,设置好x,y对应数据
g = sns.JointGrid(x = 'total_bill', y = 'tip', data = tips)
g = g.plot_joint(plt.scatter, color = 'g', s = 40, edgecolor = 'white') #绘制散点图
plt.grid(linestyle = '--')
g.plot_marginals(sns.distplot, kde = True, color = 'g')   #绘制x,y直方图

20180911142853463.png

示例3:kde - 密度图

#创建一个绘图表格区域,设置好x,y对应数据
g = sns.JointGrid(x = 'total_bill', y = 'tip', data = tips)
g = g.plot_joint(sns.kdeplot, cmap = 'Reds_r')     #绘制密度图
plt.grid(linestyle = '--')
g.plot_marginals(sns.kdeplot, shade = True, color = 'r') #绘制x,y轴密度图

20180911142959191.png

2.矩阵散点图 - pairplot()

示例1:普通矩阵图示意

#设置风格
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'], #设置不同系列的点样式(这里根据参考分类个数)
             size = 2  #图标大小
             )

20180911143255150.png

示例2:只提取局部变量进行对比

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

20180911143404114.png

示例3:其它参数设置

#其它参数设置
sns.pairplot(iris, diag_kind = 'kde', markers = '+',
             plot_kws = dict(s = 50, edgecolor = 'b', linewidth = 1),
             #设置点样式
             diag_kws = dict(shade = True)
             )#设置密度图样式

20180911143704165.png

示例4:可拆分绘制的散点图

# map_diag() + map_offdiag()
g = sns.PairGrid(iris, hue= 'species', palette = 'hls',
                 vars = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'])
                #可筛选创建一个绘图表格区域,设置好x,y对应的数据,按照species分类
#对角线图表,plt.hist/sns.kdeplot
g.map_diag(plt.hist,
           histtype = 'step', #可选:'bar','barstacked', 'step', 'stepfilled'
           linewidth = 1, edgecolor = 'w')
#其它图表:plt.scatter/plt.bar...
g.map_offdiag(plt.scatter, edgecolor = 'w', s = 40, linewidth = 1)
#设置点颜色、大小、描边宽度
g.add_legend() #添加图例()

20180911143951682.png

示例5:上三角和下三角#map_diag() + map_lower() + map_upper()

g = sns.PairGrid(iris)
g.map_diag(sns.kdeplot, lw=3) #设置对角线图表
g.map_upper(plt.scatter, color = 'r')  #设置对角线上端图表
g.map_lower(sns.kdeplot, cmap='Blues_d') #设置对角线下端图表

20180911144129387.png

相关文章
|
23小时前
|
机器学习/深度学习 算法 Python
数据分享|Python决策树、随机森林、朴素贝叶斯、KNN(K-最近邻居)分类分析银行拉新活动挖掘潜在贷款客户
数据分享|Python决策树、随机森林、朴素贝叶斯、KNN(K-最近邻居)分类分析银行拉新活动挖掘潜在贷款客户
|
1天前
|
机器学习/深度学习 算法 算法框架/工具
数据分享|PYTHON用KERAS的LSTM神经网络进行时间序列预测天然气价格例子
数据分享|PYTHON用KERAS的LSTM神经网络进行时间序列预测天然气价格例子
|
1天前
|
机器学习/深度学习 数据挖掘 网络架构
Python对商店数据进行lstm和xgboost销售量时间序列建模预测分析
Python对商店数据进行lstm和xgboost销售量时间序列建模预测分析
|
1天前
|
数据挖掘 数据处理 索引
如何使用Python的Pandas库进行数据筛选和过滤?
Pandas是Python数据分析的核心库,提供DataFrame数据结构。基本步骤包括导入库、创建DataFrame及进行数据筛选。示例代码展示了如何通过布尔索引、`query()`和`loc[]`方法筛选`Age`大于19的记录。
8 0
|
1天前
|
机器学习/深度学习 算法 数据挖掘
PYTHON银行机器学习:回归、随机森林、KNN近邻、决策树、高斯朴素贝叶斯、支持向量机SVM分析营销活动数据|数据分享-2
PYTHON银行机器学习:回归、随机森林、KNN近邻、决策树、高斯朴素贝叶斯、支持向量机SVM分析营销活动数据|数据分享
20 1
|
2天前
|
数据处理 Python
如何使用Python的Pandas库进行数据排序和排名
【4月更文挑战第22天】Pandas Python库提供数据排序和排名功能。使用`sort_values()`按列进行升序或降序排序,如`df.sort_values(by=&#39;A&#39;, ascending=False)`。`rank()`函数用于计算排名,如`df[&#39;A&#39;].rank(ascending=False)`。多列操作可传入列名列表,如`df.sort_values(by=[&#39;A&#39;, &#39;B&#39;], ascending=[True, False])`和分别对&#39;A&#39;、&#39;B&#39;列排名。
13 2
|
3天前
|
Python
如何使用Python的Pandas库进行数据缺失值处理?
Pandas在Python中提供多种处理缺失值的方法:1) 使用`isnull()`检查;2) `dropna()`删除含缺失值的行或列;3) `fillna()`用常数、前后值填充;4) `interpolate()`进行插值填充。根据需求选择合适的方法处理数据缺失。
32 9
|
5天前
|
索引 Python
如何使用Python的Pandas库进行数据透视表(pivot table)操作?
使用Pandas在Python中创建数据透视表的步骤包括:安装Pandas库,导入它,创建或读取数据(如DataFrame),使用`pd.pivot_table()`指定数据框、行索引、列索引和值,计算聚合函数(如平均分),并可打印或保存结果到文件。这允许对数据进行高效汇总和分析。
10 2
|
6天前
|
JSON 关系型数据库 数据库
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
33 0
|
6天前
|
数据可视化 数据挖掘 定位技术
Python 基于 Matplotlib 实现数据可视化(二)
Python 基于 Matplotlib 实现数据可视化(二)
19 0