Create arrows between two geom_tiles in R

28 Views Asked by At

I want to create arrows between two correlation matrices. Here's the code to create the matrices

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) 

Is it possible to automatically create such arrows as below? enter image description here

1

There are 1 best solutions below

0
stefan On

One option would be to create your arrows as a third plot which could then be combined with the correlation plots, where for convenience I use patchwork instead of 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))

enter image description here