在 R 中的两个 geom_tile 之间创建箭头

问题描述 投票:0回答:1

我想在两个相关矩阵之间创建箭头。这是创建矩阵的代码

library(gridExtra)
library(ggplot2)

X <- data.frame("x1" = rnorm(100, 0, 1),
                "x2" = rnorm(100, 0, 1),
                "x3" = rnorm(100, 0, 1))

plotCors <- function(df)
{
  ggplot(df, 
  aes(x = X1, 
      y = X2, fill = value)) +
  geom_tile() 
}

plots_list <- map(list(melt(cor(X)), melt(cor(X))), plotCors)


grid.arrange(plots_list[[1]], plots_list[[2]] +
               scale_x_discrete(limits = c("x1", "x3", "x2")) +
               scale_y_discrete(limits = c("x1", "x3", "x2")), 
             nrow = 1) 

是否可以自动创建如下箭头?

r ggplot2 grid
1个回答
0
投票

一种选择是将箭头创建为第三个图,然后可以将其与相关图结合起来,为了方便起见,我使用

patchwork
而不是
grid.arrange

library(ggplot2)
library(reshape2)
library(patchwork)

set.seed(123)

X <- data.frame(
  "x1" = rnorm(100, 0, 1),
  "x2" = rnorm(100, 0, 1),
  "x3" = rnorm(100, 0, 1)
)

plotCors <- function(df) {
  ggplot(
    df,
    aes(
      x = Var1,
      y = Var2,
      fill = value
    )
  ) +
    geom_tile()
}

plots_list <- lapply(list(melt(cor(X)), melt(cor(X))), plotCors)

p_arrow <- data.frame(
  y = c("x1", "x2", "x3"),
  yend = c("x1", "x3", "x2"),
  x = 1, xend = 2,
  group = 1:3
) |>
  ggplot(aes(x = x, xend = xend, y = y, yend = yend, group = group)) +
  geom_segment(arrow = arrow(type = "closed", length = unit(0.1, "inches"))) +
  theme_void()


plots_list[[1]] + p_arrow + plots_list[[2]] +
  scale_x_discrete(limits = c("x1", "x3", "x2")) +
  scale_y_discrete(limits = c("x1", "x3", "x2")) +
  plot_layout(guides = "collect", widths = c(2, 1, 2))

© www.soinside.com 2019 - 2024. All rights reserved.