绘制这样的相关矩阵图的最佳方法是什么?

2024-04-19

I used ggpairs to generate this plot: enter image description here

这是它的代码:

#load packages
library("ggplot2")
library("GGally")
library("plyr")
library("dplyr")
library("reshape2")
library("tidyr")


#generate example data
dat <- data.frame(replicate(6, sample(1:5, 100, replace=TRUE)))
dat[,1]<-as.numeric(dat[,1])
dat[,2]<-as.numeric(dat[,2])
dat[,3]<-as.numeric(dat[,3])
dat[,4]<-as.numeric(dat[,4])
dat[,5]<-as.numeric(dat[,5])
dat[,6]<-as.numeric(dat[,6])

#ggpairs-plot
main<-ggpairs(data=dat, 
              lower=list(continuous="smooth", params=c(colour="blue")),
              diag=list(continuous="bar", params=c(colour="blue")), 
              upper=list(continuous="cor",params=c(size = 6)), 
              axisLabels='show',
              title="correlation-matrix",
              columnLabels = c("Item 1", "Item 2", "Item 3","Item 4", "Item 5", "Item 6")) +  theme_bw() +
  theme(legend.position = "none", 
        panel.grid.major = element_blank(), 
        axis.ticks = element_blank(), 
        panel.border = element_rect(linetype = "dashed", colour = "black", fill = NA))
main

然而,我的目标是得到这样的情节:

该图是一个示例,我使用以下三个 ggplot 代码生成了它。

我将其用于 geom_point 图:

#------------------------
#lower / geom_point with jitter
#------------------------

#dataframe 
df.point <- na.omit(data.frame(cbind(x=dat[,1], y=dat[,2])))

#plot
scatter <- ggplot(df.point,aes(x, y)) +
  geom_jitter(position = position_jitter(width = .25, height= .25)) +
  stat_smooth(method="lm", colour="black") +
  theme_bw() + 
  scale_x_continuous(labels=NULL, breaks = NULL) +
  scale_y_continuous(labels=NULL, breaks = NULL) +
  xlab("") +ylab("")
scatter

this gives the following plot: enter image description here

我用它来绘制条形图:

#-------------------------
#diag. / BARCHART
#------------------------

bar.df<-as.data.frame(table(dat[,1],useNA="no"))

#Barplot
bar<-ggplot(bar.df) + geom_bar(aes(x=Var1,y=Freq),stat="identity") +
  theme_bw() + 
  scale_x_discrete(labels=NULL, breaks = NULL) +
  scale_y_continuous(labels=NULL, breaks = NULL, limits=c(0,max(bar.df$Freq*1.05))) +
  xlab("") +ylab("")
bar

This gives the following plot: enter image description here

我将其用于相关系数:

#----------------------
#upper / geom_tile and geom_text
#------------------------

#correlations
df<-na.omit(dat)
df <- as.data.frame((cor(df[1:ncol(df)]))) 
df <- data.frame(row=rownames(df),df) 
rownames(df) <- NULL 

#Tile to plot (as example)
test<-as.data.frame(cbind(1,1,df[2,2])) #F09_a x F09_b
colnames(test)<-c("x","y","var")

#Plot
tile<-ggplot(test,aes(x=x,y=y)) +
  geom_tile(aes(fill=var)) +
  geom_text(data=test,aes(x=1,y=1,label=round(var,2)),colour="White",size=10,show_guide=FALSE) +
  theme_bw() + 
  scale_y_continuous(labels=NULL, breaks = NULL) +
  scale_x_continuous(labels=NULL, breaks = NULL) +
  xlab("") +ylab("") + theme(legend.position = "none")
tile

This gives the following Plot: enter image description here

我的问题是: 获得我想要的情节的最佳方式是什么?我想将问卷中的 Likert 项目可视化,在我看来,这是一种非常好的方法。 是否可以使用 ggpairs 来实现此目的,而无需自己生成每个图,就像我对定制的 ggpairs-plot 所做的那样。或者还有其他方法可以做到这一点吗?


我不知道这是否是最好的方法,这当然并不容易,但这会生成三个图列表:条形图、散点图和图块各一个。使用gtable函数,它创建一个 gtable 布局,将绘图添加到布局中,然后进行一些微调。

EDIT:将 t 和 p.value 添加到图块中。

# Load packages
library(ggplot2)
library(plyr)
library(gtable)
library(grid)


# Generate example data
dat <- data.frame(replicate(10, sample(1:5, 200, replace = TRUE)))
dat = dat[, 1:6]
dat <- as.data.frame(llply(dat, as.numeric))


# Number of items, generate labels, and set size of text for correlations and item labels
n <- dim(dat)[2]
labels <- paste0("Item ", 1:n)
sizeItem = 16
sizeCor = 4


## List of scatterplots
scatter <- list()

for (i in 2:n) {
   for (j in 1:(i-1)) {

# Data frame 
df.point <- na.omit(data.frame(cbind(x = dat[ , j], y = dat[ , i])))

# Plot
p <- ggplot(df.point, aes(x, y)) +
   geom_jitter(size = .7, position = position_jitter(width = .2, height= .2)) +
   stat_smooth(method="lm", colour="black") +
   theme_bw() + theme(panel.grid = element_blank())

name <- paste0("Item", j, i)
scatter[[name]] <- p
} }


## List of bar plots
bar <- list()
for(i in 1:n) {

# Data frame
bar.df <- as.data.frame(table(dat[ , i], useNA = "no"))
names(bar.df) <- c("x", "y")

# Plot
p <- ggplot(bar.df) + 
   geom_bar(aes(x = x, y = y), stat = "identity", width = 0.6) +
   theme_bw() +  theme(panel.grid = element_blank()) +
   ylim(0, max(bar.df$y*1.05)) 

name <- paste0("Item", i)
bar[[name]] <- p
}


## List of tiles
tile <- list()

for (i in 1:(n-1)) {
   for (j in (i+1):n) {

# Data frame 
df.point <- na.omit(data.frame(cbind(x = dat[ , j], y = dat[ , i])))

x = df.point[, 1]
y = df.point[, 2]
correlation = cor.test(x, y)
cor <- data.frame(estimate = correlation$estimate,
                  statistic = correlation$statistic,
                  p.value = correlation$p.value)
cor$cor = paste0("r = ", sprintf("%.2f", cor$estimate), "\n", 
                 "t = ", sprintf("%.2f", cor$statistic), "\n",
                 "p = ", sprintf("%.3f", cor$p.value))


# Plot
p <- ggplot(cor, aes(x = 1, y = 1)) +
  geom_tile(fill = "steelblue") +
  geom_text(aes(x = 1, y = 1, label = cor),
     colour = "White", size = sizeCor, show_guide = FALSE) +
  theme_bw() + theme(panel.grid = element_blank()) 

name <- paste0("Item", j, i)
tile[[name]] <- p
} }


# Convert the ggplots to grobs, 
# and select only the plot panels
barGrob <- llply(bar, ggplotGrob)
barGrob <- llply(barGrob, gtable_filter, "panel")

scatterGrob <- llply(scatter, ggplotGrob)
scatterGrob <- llply(scatterGrob, gtable_filter, "panel")

tileGrob <- llply(tile, ggplotGrob)
tileGrob <- llply(tileGrob, gtable_filter, "panel")


## Set up the gtable layout
gt <- gtable(unit(rep(1, n), "null"), unit(rep(1, n), "null"))


## Add the plots to the layout
# Bar plots along the diagonal
for(i in 1:n) {
gt <- gtable_add_grob(gt, barGrob[[i]], t=i, l=i)
}

# Scatterplots in the lower half
k <- 1
for (i in 2:n) {
   for (j in 1:(i-1)) {
gt <- gtable_add_grob(gt, scatterGrob[[k]], t=i, l=j)
k <- k+1
} }

# Tiles in the upper half
k <- 1
for (i in 1:(n-1)) {
   for (j in (i+1):n) {
gt <- gtable_add_grob(gt, tileGrob[[k]], t=i, l=j)
k <- k+1
} }


# Add item labels
gt <- gtable_add_cols(gt, unit(1.5, "lines"), 0)
gt <- gtable_add_rows(gt, unit(1.5, "lines"), 2*n)

for(i in 1:n) {
textGrob <- textGrob(labels[i], gp = gpar(fontsize = sizeItem)) 
gt <- gtable_add_grob(gt, textGrob, t=n+1, l=i+1)
}

for(i in 1:n) {
textGrob <- textGrob(labels[i], rot = 90, gp = gpar(fontsize = sizeItem)) 
gt <- gtable_add_grob(gt, textGrob, t=i, l=1)
}


# Add small gap between the panels
for(i in n:1) gt <- gtable_add_cols(gt, unit(0.2, "lines"), i)
for(i in (n-1):1) gt <- gtable_add_rows(gt, unit(0.2, "lines"), i)


# Add chart title
gt <- gtable_add_rows(gt, unit(1.5, "lines"), 0)
textGrob <- textGrob("Korrelationsmatrix", gp = gpar(fontface = "bold", fontsize = 16)) 
gt <- gtable_add_grob(gt, textGrob, t=1, l=3, r=2*n+1)


# Add margins to the whole plot
for(i in c(2*n+1, 0)) {
gt <- gtable_add_cols(gt, unit(.75, "lines"), i)
gt <- gtable_add_rows(gt, unit(.75, "lines"), i)
}


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

绘制这样的相关矩阵图的最佳方法是什么? 的相关文章

  • grid.arrange 中的错误 -rangeGrob() 函数

    我有两个图 p1 和 p2 我试图使用 grid arrage 绘制它们 我的代码如下所示 grid arrange p1 p2 ncol 2 top textGrob Distribution across each day of the
  • 当测试集中不存在响应变量时,h2o 预测有时会失败

    当在不存在响应变量的测试集上进行预测时 如果在训练中对因子变量使用一种热编码 则 h2o 会以各种不同的方式失败 无论是在训练 GLM 时隐式指定还是在其他方法中显式指定时 R 3 4 0 和 h2o 3 12 0 1 中存在此错误 我们还
  • 使用 stargazer 分析包含时间序列的数据帧

    我有一个面板数据集共 10 个观测值和 3 个变量 观测值 30 的数量 10 行 国家 地区 2 列 迁移参数 相应年份的 1 列 可以这么说 我的数据框由 3 个年度数据框组成 我该如何申请观星者考虑到它是一个面板数据集 所以最大 N
  • 建模前减少因子水平数量

    我有一个 2600 个级别的因子 我想在建模之前将其减少到 10 我想我可以通过这样的操作来做到这一点 如果一个因素列出的次数少于 x 次 则应将其放入名为 其他 的存储桶中 这是一些示例数据 df lt data frame colour
  • 栅格堆叠后如何写入?

    我想操作几个光栅文件 然后再次写入它们 rasterfiles lt list files C data envi full names TRUE d1 lt overlay stack rasterfiles fun function x
  • 编写健壮的 R 代码:命名空间、屏蔽和使用 `::` 运算符

    简洁版本 对于那些不想阅读我的 案例 的人来说 这就是本质 最小化新包破坏现有代码 即编写您编写的代码 的机会的推荐方法是什么尽可能坚固 充分利用该功能的推荐方法是什么 命名空间机制 when a just using贡献的软件包 比如在一
  • 将天气 iframe 嵌入到 Shiny Dashboard 中

    我正在尝试将 Forecast io 的天气预报嵌入到闪亮的仪表板中 我最初在使用 符号时遇到了麻烦 但看到一篇文章提供了如何使用特殊字符格式化 HTML 代码的示例 但是 当我运行该应用程序时 我看到一个简单的 未找到 即使我知道该链接有
  • 以编程方式触发 R 传单中的标记鼠标单击事件以获得闪亮效果

    我的问题与此相同 在 R 传单中触发标记鼠标单击事件以获得闪亮效果 https stackoverflow com questions 56962857 trigger marker mouse click event in r leafl
  • R:编写抛硬币的随机采样程序

    假设我们有以下情况 有一枚硬币 如果它正面朝上 那么下一次抛掷正面的概率是 0 6 如果是反面 那么下一次抛掷反面的概率也是 0 6 一个班有100名学生 每个学生随机抛掷硬币几次 Student n 的最后一次抛硬币不会影响 Studen
  • 从向量中删除元素在 R 中出现的时间量

    我想从一个向量中删除元素在另一个向量中出现的时间 就像我要减去它们一样 鉴于我想要删除的元素向量中的每个元素也存在于我想要从中删除的主向量中 a lt c A B B C C C b lt c A B C C a a in b return
  • 将 RDS 文件从网络(即 URL)直接加载到 R 中?

    read csv 具有直接从 url 读取的出色能力 readRDS 才不是 我想将 RDS 文件从 Internet 移动到我的 R 环境 我看到有几种方法 Method 1 此方法会用下载的文件弄乱工作目录 myurl lt https
  • 如何从R中的日期中提取月份

    我正在使用lubridate封装并应用month从日期中提取月份的函数 我在日期字段上运行了 str 命令 得到了 Factor w 9498 levels 01 01 1979 01 01 1980 5305 1 1 1 1 1 1 1
  • Django 中的 Rpy2 错误 - 未为“”类型的对象定义转换“py2rpy”

    我以前从未使用过 R 并且正在尝试使用 rpy2 从 python 调用 R 函数 它可以在独立的 python 终端上运行 但不能在 Django 中运行 但rpy2似乎无法将python字符串转换为r对象 我正在使用同事提供的自定义库
  • matplotlib 中的 R 风格数据轴缓冲区

    R 绘图自动设置 x 和 y 限制 以在数据和轴之间留出一些空间 我想知道 matplotlib 是否有办法自动执行相同的操作 如果没有 是否有一个好的公式或 经验法则 来说明 R 如何设置其轴限制 在 matplotlib 中 您可以通过
  • stat_function 从函数生成平线

    我有以下代码 library ggplot2 f lt function x if x gt 2 1 x 0 3 else 0 graph lt ggplot data frame x c 0 10 aes x graph lt graph
  • 使用自定义渐变填充直方图箱

    我想在 R 和 ggplot2 中创建一个直方图 其中根据连续的 x 值填充箱 大多数教程仅通过离散值或密度 计数进行着色 下列的这个例子 https stackoverflow com questions 40284227 how to
  • 美人鱼图:调整图表周围的空白

    我在用 Rstudio 编译的 Rmd 报告中使用了美人鱼图 在 HTML PDF 输出中 图表上方和下方有大量空白 请参见下面的示例 Header Text r library DiagrammeR mermaid graph TD cl
  • 如何有效地将多个光栅 (.tif) 文件导入 R

    我是 R 新手 尤其是在空间数据方面 我正在尝试找到一种方法来有效地将多个 600 单波段栅格 tif 文件导入到 R 中 所有文件都存储在同一文件夹中 不确定这是否重要 但请注意 在我的 Mac 和 Windows 并行 VM 上的文件夹
  • R data.table 连接不等式条件

    我想使用 data table 包根据多个不等式条件对数据进行子集化 data table 手册中的示例展示了如何使用字符变量执行此操作 但不显示数字不等式 我还了解了如何使用子集函数来执行此操作 但我真的很想利用 data table 二
  • R闪亮:使用闪亮的JS从数据表中获取信息

    我想读出所有列名称以及它们在数据表中显示的顺序 由于不同的原因 我无法使用 stateSave 等选项 我对 JS 没有什么把握 但我确信用它可以完成 所以我需要你帮助我 我尝试过类似的代码片段 datatable data callbac

随机推荐