GGally与pairs相关关系图_史上最全(二)

2023-11-20

640?wx_fmt=png

作者:李誉辉  

四川大学在读研究生


接上一篇:GGally与pairs相关关系图_史上最全(一)


2.4

 wrap()封装


其它需要指定到geom_xxx()中的参数,可以通过wrap()传递给lower,upper, 或diag

 语法:

1wrap(funcVal, ..., funcArgName = deparse(substitute(funcVal)))
2wrapp(funcVal, params = NULL, funcArgName = deparse(substitute(funcVal)))


解释:

  • wrap()为参数传递,wrapp()为列表传递。

  • funcVal, 表示需要见参数传递给什么类型的对象,
    ggally_points"points"则将参数传递给散点图;
    ggally_facetdensity"facetdensity"则将参数传递给分面密度图。

  • ...params,表示要传递的参数,都是geom_xxx()中的参数,
    alphasizebinwidth


 1library(GGally)
2library(ggplot2)
3diamonds.samp <- diamonds[sample(1:dim(diamonds)[1], 1000), ]
4
5# 下面是plots超过15个,为16个,所以默认产生进度条
6ggpairs(
7  diamonds.samp[, c(1:2,5,7)],
8  mapping = aes(color = cut),
9  diag = list(
10    continuous = wrap("densityDiag",alpha = 0.5)), # 给对角线的密度图增加透明度参数
11  title = "wrap()传递透明度参数给对角线上的密度图"
12)
13


640?wx_fmt=png

 1require(GGally)
2data(tips, package="reshape")
3g1 <- 
4  ggpairs(data = tips, mapping = aes(colour = sex),
5    lower = list(
6      continuous = wrap(ggally_points, alpha = 0.5), # 增加透明度参数
7      combo = wrap("facethist", binwidth = 0.5) # 增加柱子宽度参数
8      ), 
9    diag = list(
10      continuous = wrap(ggally_densityDiag, alpha = 0.5) # 增加透明度参数
11    ),
12    title="下三角散点图增加透明度,直方图设置宽度,对角线面积图增加透明度"
13  )
14g1
15


640?wx_fmt=png


 1wrap_1 <- wrap(ggally_pointssize = 5, color = "magenta"alpha = 0.3)
2wrap_2 <- wrap(ggally_densityDiagsize = 2, color = "lightgreen")
3wrap_3 <- wrap(ggally_corsize = 8, color = "pink"fontface = "bold")
4
5ggpairs(iris1:3
6        lower = list(continuous = wrap_1),
7        diag = list(continuous = wrap_2),
8        upper = list(continuous = wrap_3),
9        title = "设置点的:透明度,颜色大小;线的:颜色,线宽;字的:字型,颜色,尺寸"
10        )
11


640?wx_fmt=png



2.5

自定义主题


 1library(GGally)
2library(ggplot2)
3library(showtext)
4
5# 添加字体
6windowsFonts(YaHei_rontine = windowsFont("微软雅黑"))
7font_add("YaHei_rontine", regular = "msyh.ttc", bold = "msyhbd.ttc")  
8
9wrap_1 <- wrap(ggally_pointssize = 5, color = "magenta"alpha = 0.3)
10wrap_2 <- wrap(ggally_densityDiagsize = 2, color = "lightgreen")
11wrap_3 <- wrap(ggally_corsize = 8, color = "pink"fontface = "bold")
12
13gg_1 <- ggpairs(iris1:3
14                lower = list(continuous = wrap_1),
15                diag = list(continuous = wrap_2),
16                upper = list(continuous = wrap_3),
17                title = "自定义主题:红色雅黑字体居中"
18        ) 
19
20gg_1 + theme_bw() + 
21  theme(plot.title = element_text(size = 20, color = "red"hjust = 0.5,
22                                  family = "YaHei_rontine"))
23


640?wx_fmt=png


2.6

scale_xxx()标度调整


只能索引出来子集后调整子集的标度。


 1library(ggplot2)
2library(GGally)
3data(tips, package = "reshape")
4
5mygg <- ggpairs(tipsmapping = aes(color = day),
6                columns = c("total_bill", "time", "tip"),
7                columnLabels = c("Total_Bill(连续变量)", "Time(离散变量)", "Tip(连续变量)"),
8                diag = list(continuous = wrap(ggally_densityDiag, alpha = 0.7)),
9                title = "修改单个plot的标度"
10)
11
12mygg[1,1] <- mygg[1,1] + scale_fill_brewer(palette = "Set2")
13mygg[2,2] <- mygg[2,2] + scale_fill_brewer(palette = "Dark2")
14mygg[3,3] <- mygg[3,3] + scale_fill_brewer(palette = "Set1")
15
16mygg + theme_bw() + 
17  theme(plot.title = element_text(size = 20, color = "red"hjust = 0.5,
18                                  family = "YaHei_rontine"))
19


640?wx_fmt=png


 1gg_2 <- ggpairs(iris, aes(color = Species),
2                title = "循环给每个plot修改标度"
3                ) 
4
5# 循环给每一个子集plot修改标度
6for(i in 1:gg_2$nrow) {
7  for(j in 1:gg_2$ncol){
8    gg_2[i,j] <- gg_2[i,j] + 
9        scale_fill_manual(values=c("#7fc97f""#beaed4""#fdc086")) +
10        scale_color_manual(values=c("#7fc97f""#beaed4""#fdc086"))  
11  }
12}
13gg_2 + theme_bw() + 
14  theme(plot.title = element_text(size = 20, color = "red", hjust = 0.5,
15                                  family = "YaHei_rontine"))


640?wx_fmt=png


2.7

 legend图例


 1library(ggplot2)
2library(GGally)
3data(tips, package = "reshape")
4
5gg_3 <- ggpairs(tips, mapping = aes(color = day),
6                columns = c("total_bill""time""tip"),
7                columnLabels = c("Total_Bill(连续变量)""Time(离散变量)""Tip(连续变量)"),
8                diag = list(continuous = wrap(ggally_densityDiag, alpha = 0.7)),
9                legend = c(2,2), 
10                title = "设置图例"
11)
12
13for(i in 1:gg_3$nrow) {
14  for(j in 1:gg_3$ncol){
15    gg_3[i,j] <- gg_3[i,j] + 
16        scale_fill_brewer(palette = "Set2") + 
17        scale_color_brewer(palette = "Set2"
18  }
19}
20
21gg_3 + theme_bw() + 
22  theme(plot.title = element_text(size = 20, color = "red", hjust = 0.5,
23                                  family = "YaHei_rontine"),
24        legend.position = "right")


640?wx_fmt=png


 1library(ggplot2)
2library(GGally)
3data(tips, package = "reshape")
4
5# 提取图例
6mylegend <- grab_legend(ggplot(tips, aes(x = total_bill, fill = day)) + 
7                          geom_density() + 
8                          scale_fill_brewer(palette = "Set2")
9                       )
10
11gg_3 <- ggpairs(tips, mapping = aes(color = day),
12                columns = c("total_bill""time""tip"),
13                columnLabels = c("Total_Bill(连续变量)""Time(离散变量)""Tip(连续变量)"),
14                diag = list(continuous = wrap(ggally_densityDiag, alpha = 0.7)),
15                legend = mylegend, 
16                title = "grab_legend提取图例"
17)
18
19for(i in 1:gg_3$nrow) {
20  for(j in 1:gg_3$ncol){
21    gg_3[i,j] <- gg_3[i,j] + 
22        scale_fill_brewer(palette = "Set2") + 
23        scale_color_brewer(palette = "Set2"
24  }
25}
26
27gg_3 + theme_bw() + 
28  theme(plot.title = element_text(size = 20, color = "red", hjust = 0.5,
29                                  family = "YaHei_rontine"),
30        legend.position = "left")


640?wx_fmt=png



3.ggscatmat()

语法:


1ggscatmat(data, columns = 1:ncol(data), color = NULL, alpha = 1,
2  corMethod = "pearson")


解释:

  • ggscatmat()非常简单,功能也非常单一,运算速度比ggpairs更快,
    只能使用连续变量,也就产生下三角为散点图,上三角为相关系数,对角线为密度图。

  • color,表示指定颜色变量。

  • alpha,指定散点图的透明度,默认为1(不透明)。

  • corMethod, 表示指定相关系数的计算方法,默认"pearson",还有"kendall""spearman"


1library(ggplot2)
2library(GGally)
3
4ggscatmat(tips, columns = c("total_bill""tip""size"), # 变量名指定
5          color="day", alpha = 0.8)
6
7ggscatmat(tips, columns = c(1,2,7), # 索引值指定
8          color="day", alpha = 0.8)


640?wx_fmt=png

640?wx_fmt=png


4.pairs()

前面介绍了ggpairs及相关的绘图函数,接下来,我们将介绍graphics包中的pairs()函数。


语法:

 1pairs(formula, data = NULL..., subset,
2      na.action = stats::na.pass)
3
4pairs(x, labels, panel = points, ...,
5      horInd = 1:nc, verInd = 1:nc,
6      lower.panel = panel, upper.panel = panel,
7      diag.panel = NULL, text.panel = textPanel,
8      label.pos = 0.5 + has.diag/3, line.main = 3,
9      cex.labels = NULL, font.labels = 1,
10      row1attop = TRUE, gap = 1, log = "")


关键参数:

  • x, 数据矩阵或数据框,其中逻辑和因子型变量会被强制转换为数值型。

  • formula, 形如~x + y + z的公式,x,y,z分别代表多个数值变量。

  • data, formula中,变量所在的数据框或列表。

  • subset, 指定进行可视化的观测。

  • horInd,verInd,表示用索引值指定要绘图的变量。

  • na.action, 指定缺失值的处理方式。

  • labels, 变量名称(给变量贴标签)。

  • panel, 自定义面板函数。

  • lower.panelupper.panel,自定义上三角和下三角面板中的绘图函数。

  • diag.panel, 指定主对角线面板上的作图函数。

  • text.panel, 指定主对角线面板上文本标签的函数。

  • label.pos, 指定文本标签的位置。

  • cex.labelsfont.labels, 指定文本标签的缩放倍数及字体样式。

  • rowlattop, 逻辑值,指定散点图第一行出现在顶部还是底部。

  • main, 指定标题。

  • gap, 指定子区域之间的间距。

  • log, 表示对坐标轴进行对数变换,log = "x"表示x轴对数变换,log="y"表示对y轴对数变换;
    log = "xy"表示x,y同时对数变换。 log = 1:4 表示前4个变量对数变换。

  • ...,其它要传递的绘图参数,一般是par()中的参数。



4.1

默认绘图样式


1library(graphics)
2head(iris) # 前4列为数字变量
3
4pairs(iris[1:4], main = "默认样式"# 默认绘图样式


640?wx_fmt=png


640?wx_fmt=png


4.2

自定义panel


 1library(grDevices)
2
3head(mtcars)
4df <- mtcars[, c(1,3:6)]
5
6# 定义上三角panel
7panel_upper <- function(x, y, digits = 2, col, ...) {
8  usr <- par("usr"); on.exit(par(usr))
9  par(usr = c(0101))
10  # 文本颜色
11  text_color <- if(cor(x, y) > 0) {"black"else {"white"# 大于0为黑色,小于0为白色
12  # 文本内容
13  txt <- round(cor(x,y), 2# 保留2位小数
14  # 背景颜色
15  col_index <- if (cor(x,y) > 0) {(1 - cor(x,y))} else {(1 + cor(x,y))}
16  bg_col <- if (cor(x,y) > 0) {
17    rgb(red = 1, green = col_index, blue = col_index)
18  } else { rgb(red = col_index, green = col_index, blue = 1)}
19  # 绘图
20  rect(xleft = 0, ybottom = 0, xright = 1, ytop = 1, col = bg_col) # rect画背景
21  text(x = 0.5, y = 0.5, labels = txt, cex = 2, col = text_color)
22}
23
24# 定义下三角panel
25panel_lower <- function(x, y, bg = NA, pch = par("pch"),
26                     cex = 1, col_smooth = "blue",...)
 
{
27     points(x, y, pch = pch, bg = bg, cex = cex)
28     abline(stats::lm(y ~ x), col = col_smooth,...)
29}
30
31
32# 绘图
33pairs(df, main = "自定义panels",
34  pch = 21
35  upper.panel = panel_upper,
36  lower.panel = panel_lower
37)


640?wx_fmt=png


640?wx_fmt=png


do.call()调用:


 1panel_upper <- function(x, y, digits = 2, bg = NULL, col = NULL, ...) {
2  u <- par("usr")
3  names(u) <- c("xleft""xright""ybottom""ytop")
4  # 背景颜色: 要求,相关系数大于0为红色渐变,小于0为蓝色渐变
5  col_index <- if (cor(x,y) > 0) {(1 - cor(x,y))} else {(1 + cor(x,y))}
6  bg_col <- if (cor(x,y) > 0) {
7    rgb(red = 1, green = col_index, blue = col_index)
8  } else { rgb(red = col_index, green = col_index, blue = 1)}
9  do.call(rect, c(col = bg_col, as.list(u))) 
10  par(usr = c(0101))
11  # 文本颜色:要求相关系数大于0为黑色,小于0为白色
12  text_color <- if(cor(x, y) > 0) {"black"else {"white"# 大于0为黑色,小于0为白色
13  # 文本内容
14  txt <- round(cor(x,y), 2# 保留2位小数
15  # 绘图
16  text(x = 0.5, y = 0.5, labels = txt, cex = 2, col = text_color)
17}
18
19# 绘图
20pairs(df, main = "自定义panels",
21  pch = 21
22  upper.panel = panel_upper,
23  lower.panel = panel_lower
24)


640?wx_fmt=png


考资料


  • R语言相关关系可视化函数梳理

    https://zhuanlan.zhihu.com/p/36925332

  • 相关性分析了解一下

    https://mp.weixin.qq.com/s/Nm9NEGG9gy-lEX34kyxFgQ?token=1086251536&lang=zh_CN

  • R手册(Visualise)–GGally(ggplot2 extensions)

    https://blog.csdn.net/qq_41518277/article/details/80517791

  • Plot Multivariate Continuous Data

    http://www.sthda.com/english/articles/32-r-graphics-essentials/130-plot-multivariate-continuous-data/

  • Scatter Plot Matrices - R Base Graphs

    http://www.sthda.com/english/wiki/scatter-plot-matrices-r-base-graphs

  • R Exploratory Analysis with ggpairs

    http://timothykylethomas.me/ggpairs.html#1_overview

  • ggpairs 参数

    https://www.rdocumentation.org/packages/GGally/versions/1.4.0/topics/ggpairs

  • DT包用法

    https://rstudio.github.io/DT/

  • R语言相关关系可视化函数梳理

    http://developer.51cto.com/art/201805/573479.htm

  • R语言学习系列19-基本统计图形

    https://wenku.baidu.com/view/cfcff51fc4da50e2524de518964bcf84b9d52dc

  • R语言中用pairs作图时标出各个分图中的所要显示的点

    https://blog.csdn.net/faith_mo_blog/article/details/39694897

  • R 学习笔记: Par 函数

    https://zhuanlan.zhihu.com/p/21394945

  • Scatter Plot Matrices - R Base Graphs

    http://www.sthda.com/english/wiki/scatter-plot-matrices-r-base-graphs


——————————————

往期精彩:

640?wx_fmt=png

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

GGally与pairs相关关系图_史上最全(二) 的相关文章

  • 日志清理脚本

    需求背景 解决某些中间件或者应用日志无法自动清理的情况 比如 Nacos 的 access 日志清理 临时目录文件清理等 简介 Filename clear logs sh Revision 0 0 3 Date 2020 06 05 Au
  • 探究Xcode New Build System对于构建速度的提升

    在Xcode9发布的时候 Apple在Build System上提供了新版本的构建系统 New Build System 具体可见WWDC2017 不过令人失望的是 该新特性的讲解很简短 短到只在一页PPT上露脸 在这短短的时间里 苹果讲述
  • Python 生成器如何设置和使用

    Python 的生成器其实可以理解为一种比较复杂的迭代器 关于迭代器 可以参考 Python 迭代器的设置和使用方法 一 代码举例 def gen x y txt I love x yield txt txt 1 You love y yi
  • 作用域和内存问题

    文章目录 一 基本类型和引用类型的值 基本类型和引用类型的区别 1 动态的属性 2 复制变量值 3 传递参数 4 监测类型 二 执行环境及作用域 1 延长作用域链 2 没有块级作用域 一 基本类型和引用类型的值 变量可能包括两种不同的数据类
  • 【Docker】之安装 Redis

    一 下载 Redis 镜像 下载最新版 Redis 镜像 默认版本为 latest docker pull redis 更多版本镜像 1 访问 Docker 官网 https hub docker com 在镜像搜索栏中输入 Redist
  • flea-auth使用之用户子模块介绍

    用户子模块 本篇主要介绍笔者 授权模块 flea auth 下的用户子模块 1 总览 表名 中文描述 flea account 账户 flea account attr 账户扩展属性 flea user 用户 flea user attr
  • libevent的消息传递和回调注册函数

    参考原帖地址 https www cnblogs com secondtonone1 p 5554075 html 1 evconnlistener new bind函数 1 evconnlistener new bind 完成socket
  • JDK8下载安装

    参考 JDK8下载安装教程 涵涵想养猫的博客 CSDN博客 jdk8下载安装 下载地址 https www oracle com java technologies javase javase jdk8 downloads html 根据需
  • python 中 os._exit(), sys.exit()

    1 os exit 不抛异常 后面的代码就不执行了 不执行相关清理工作 直接退出 Python 解释器一般来说用在子线程中退出 2 sys exit 引发一个 SystemExit 异常 没有捕获这个异常 会直接退出 捕获这个异常可以做一些
  • 软考:中级软件设计师:程序语言基础:表达式,标准分类,法律法规,程序语言特点,函数传值传址

    软考 中级软件设计师 程序语言基础 表达式 提示 系列被面试官问的问题 我自己当时不会 所以下来自己复盘一下 认真学习和总结 以应对未来更多的可能性 关于互联网大厂的笔试面试 都是需要细心准备的 1 自己的科研经历 科研内容 学习的相关领域
  • 禁止ios浏览器页面上下滚动 (橡皮筋效果)弹性滚动 微信的下拉回弹

    发现之前阻止页面滚动的代码e preventDefault代码失效了 于是自己折腾了一番 找到了解决办法 一 前言 浏览器在移动端有一个默认触摸滚动的效果 让我们感触最深的莫过于微信浏览器里面 下拉时自带橡皮筋的效果 然而在开发的时候我们经
  • 软件测试日常分享

    以下是测试主管 测试经理 质量保证经理的面试问题和答案 供新人和有经验的求职者获得他们梦想的工作 1 测试经理的职责是什么 QA经理的角色包括 从启动到结束管理项目 测试计划 获得客户对交付成果的认可 向客户端批准中间交付物和补丁发布 提交
  • 动手学深度学习——softmax回归(原理解释+代码详解)

    目录 1 softmax回归 1 1 分类问题 1 2 网络架构 1 3 全连接层的参数开销 1 4 softmax运算 1 5 小批量样本的矢量化 1 6 损失函数 1 6 1 对数似然 1 6 2 softmax及其导数 1 6 3 交
  • 算法导论 学习笔记 第七章 快速排序

    快排最坏时间复杂度为 n 但它的平均性能很好 通常是实际排序应用中最好的选择 它的期望时间复杂度为 nlgn 且 nlgn 中隐含的常数因子非常小 且它还能进行原址排序 快排也使用了分治思想 1 分解 数组被划分为两个子数组 使得一个子数组
  • 服务器如何开多个虚拟机,服务器运行多个虚拟机

    服务器运行多个虚拟机 内容精选 换一换 通过内网连接云手机实例时 需要在租户VPC中创建一台弹性云服务器 作为连接云手机的跳板机器 若创建云手机服务器时未使用自定义网络 还需在云手机租户的VPC和服务器所在VPC之间建立对等连接 如图1所示
  • SpringBoot集成Netty时在Handler类中注入service和dao为null

    最近在做一个服务器接收客户端消息 之前一直都只接触web开发 第一次接触服务器开发 接触到Netty 但在Netty的Handler类里注入为null public class HttpRequestHandler extends Simp
  • 【vue3练习 -12】vue3使用readonly(),shallowReadonly()

    作用 把一个响应式 可以是ref定义的 也可以是reactive定义的 的数据变成只读的 不可以修改 使用场景 假如你的组件有个数据 但是你不希望在使用的时候修改他就可以把他变成只读的 用法示例 import readonly shallo
  • SOLO算法解读

    论文 SOLO Segmenting Objects by Locations 论文链接 https arxiv org abs 1912 04488 代码链接 GitHub WXinlong SOLO SOLO and SOLOv2 fo
  • 安全之安全(security²)博客目录导读

    研究方向 安全之安全 研究内容 ARM RISC V安全架构 TF A TEE之安全 GP安全认证 静态代码分析 FUZZ模糊测试 IDA逆向分析 安全与功耗等 欢迎您的关注 一 ARM安全架构 1 ARM安全架构及其发展趋势 转载 2 A
  • uc同步登陆同步退出

    几乎每个应用在整合UC的时候都会遇到无法同步登陆同步退出的情况 今天分析下原因 首先我们的项目会将uc client这个文件夹原封不动的拷贝到项目根目录 public function inteLogin loginname passwor

随机推荐