我不确定此类绘图的正确名称是什么,但是可以说我们有一个名称列表(或此处的字母):data <- data.frame(letters[1:10])
还要说,我们要根据一些经验决定来说明这些名称中的哪些是关联的,因此我们有一个列表,希望将其连接到如下图中(在powerpoint中完成):
这可以在ggplot中完成吗?
答案 0 :(得分:3)
是的,可以在ggplot中完成。
让我们开始建立一个字母数据框架,并在图表的x和y轴上关联位置。我们将x值设为1和2(尽管这是任意的),并将y值设为1:10(也可以是任意的,只要它们均匀间隔即可)
labels <- data.frame(x = c(rep(1, 10), rep(2, 10)),
y = rep(1:10, 2),
labs = rep(LETTERS[10:1], 2),
stringsAsFactors = FALSE)
现在,我们还需要某种方法来确定将要加入的字母。为此,我们使用一个简单的数据框,该数据框包含“ left”和“ right”值,其中每行描述将要连接的两个字母:
set.seed(69)
joins <- data.frame(left = sample(LETTERS[1:10], 6, TRUE),
right = sample(LETTERS[1:10], 6, TRUE),
stringsAsFactors = FALSE)
joins
#> left right
#> 1 A G
#> 2 B B
#> 3 H J
#> 4 G D
#> 5 G J
#> 6 F B
现在,我们可以通过将这两列中的字母与labels
数据框中的列进行匹配,来为行指定x和y的起点和终点坐标:
joins$x <- rep(1.05, nrow(joins))
joins$xend <- rep(1.9, nrow(joins))
joins$y <- labels$y[match(joins$left, labels$labs)]
joins$yend <- labels$y[match(joins$right, labels$labs)]
这只是情节。我们希望摆脱所有轴,标题和图例,因此我们使用theme_void
:
library(ggplot2)
ggplot(labels, aes(x, y)) +
geom_text(aes(label = labs), size = 8) +
geom_segment(data = joins, aes(xend = xend, yend = yend, color = left),
arrow = arrow(type = "closed", length = unit(0.02, "npc"))) +
coord_cartesian(xlim = c(0.5, 2.5)) +
theme_void() +
theme(legend.position = "none")
由reprex package(v0.3.0)于2020-07-10创建
答案 1 :(得分:1)
可以解决此解决方案,但是可以开始使用geom_segment
library(tidyverse)
tibble(x0 = 0, x1 = 1, y0 = sample(letters[1:10]), y1 = sample(letters[1:10])) %>%
mutate(y0 = factor(y0, levels = rev(letters[1:10])),
y1 = factor(y1, levels = rev(letters[1:10]))) %>%
ggplot(aes(x = x0, xend = x1, y = y0, yend = y1)) +
geom_segment(arrow = arrow(length = unit(0.03, "npc"))) +
geom_text(aes(x = x1, y = y1, label = y1), nudge_x = 0.01)