很遗憾,在ggplot2 2.x版本中,这种方法已经失效。
以下代码正好提供了我想要的内容,但需要进行一些额外的前期计算:
library(ggplot2)
library(data.table)
orderX <- c("A" = 1, "B" = 2, "C" = 3)
y <- rnorm(20)
x <- as.character(1:20)
group <- c(rep("A", 5), rep("B", 7), rep("C", 5), rep("A", 3))
dt <- data.table(x, y, group)
dt[, lvls := as.numeric(orderX[group])]
dt[, average := mean(y), by = group]
dt[, x := reorder(x, lvls)]
dt[, xbegin := names(which(attr(dt$x, "scores") == unique(lvls)))[1], by = group]
dt[, xend := names(which(attr(dt$x, "scores") == unique(lvls)))[length(x)], by = group]
ggplot(data = dt, aes(x=x, y=y)) +
geom_point(aes(colour = group)) +
facet_grid(.~group,space="free",scales="free_x") +
geom_segment(aes(x = xbegin, xend = xend, y = average, yend = average, group = group, colour = group))
生成的图片:
![在此输入图片描述](https://istack.dev59.com/HhRfQ.webp)