r - 绘制表格和连接它们的箭头

标签 r ggplot2

我想知道是否可以使用 ggplot2 绘制类似下面示例的内容。如果没有,能否请您指导我使用合适的工具在 R 中完成此操作?谢谢!

enter image description here

最佳答案

简短回答:是的,当然有可能。这在一定程度上取决于您的用例是什么,取决于您想要放入其中的自动化程度。棘手的一点显然是箭头位,在尝试自动化方法时它变得有点复杂,所以我会把它留给你 - 只是展示在 ggplot2 中获得它的一种原则方法。

library(tidyverse)
ls_tbl <- replicate(3, data.frame(label = paste0("Field", 5:1)), simplify = FALSE)
## make the data frames for tables and rects
ls_df <- lapply(seq_along(ls_tbl), function(i){
  df <- rbind(ls_tbl[[i]], paste0("Table", i))
  df$y <- seq_len(nrow(df))
  df$x <- i
  df_rect <- data.frame(xmin = i-.2, xmax = i+.2, ymin = min(df$y)-.5, ymax = max(df$y)+.5)
  y_seg <-  (df$y[length(df$y)] + df$y[length(df$y)-1])/2
  df_seg <- data.frame(x = i-.2, xend = i+.2, y =y_seg, yend = y_seg)
  setNames(list(df, df_rect, df_seg), c("text", "rect", "seg"))
})
## draw arrows, this can be automated based on the position of fields and tables
## that's not suuuuper straight forward, so I won't do that here
arrow_df <- data.frame(x = c(1, 3), xend = rep(2, 2), y = c(5, 5), yend = c(2, 4)) %>%
  mutate(x = ifelse(xend > x, x + .2, x - .2), 
         xend = ifelse(xend > x, xend- .2, xend + .2))

## now plotting fun
ggplot() +
  geom_rect(data = bind_rows(map(ls_df, "rect")), color = "black", fill = NA,
            aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax)) +
  geom_segment(data = bind_rows(map(ls_df, "seg")), aes(x, y, xend = xend, yend = yend))+
  geom_text(data = bind_rows(map(ls_df, "text")), aes(x, y, label = label)) +
  geom_segment(data = arrow_df, arrow = arrow(type = "closed"), 
               aes(x, y, xend = xend, yend = yend)) +
  theme_void()

reprex package 创建于 2021-12-24 (v2.0.1)

关于r - 绘制表格和连接它们的箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68711765/

相关文章:

r - 如何将抖动添加到 ggpairs 中的散点图矩阵?

r - 我们如何使用 R 将数据写入 postgres 数据库表?

r - 使用 ggplot2 绘制圆形密度图

r - 将参数传递给闭包(?)

r - 在 Ubuntu 18.04 LTS 上安装 R 3.5.0

r - 在 R 中使用 ggplot 在绘图上绘制形状?

r - 如何合并两个数据框并提取列的唯一组合?

r - 如何使用 ggplot2 控制绘图的尺寸/大小

r - 仅对 geom_bar 中的选定栏使用不同的颜色

r - 从 github 安装 ggthemes r-package 开发者版本时出错