如何根据构面组调整每个geom_line
的高度(y-lims因组而异,请参见下图)?
我尝试构建一个自定义data.frame,其中包含每个条件的高度,但geom_line
不接受此。
我有一个小小的工作示例:
carData <- mtcars
carData$cyl <- factor(carData$cyl)
maxval <- max(carData$mpg)
maxval <- maxval * 1.1
lowval <- maxval - maxval * 0.02
txtval <- maxval * 1.04
llev <- "4"
rlev <- "6"
lpos <- which(levels(carData$cyl) == llev)
rpos <- which(levels(carData$cyl) == rlev)
mpos <- (lpos + rpos) / 2
df1 <- data.frame(a = c(lpos,lpos,rpos,rpos), b = c(lowval, maxval, maxval, lowval))
p <- ggplot(carData, aes(cyl, mpg))
p <- p + geom_boxplot()
p <- p + geom_line(data = df1, aes(x = a, y = b)) + annotate("text", x = mpos, y = txtval, label = "3.0")
p <- p + facet_wrap( ~ gear,ncol=2,scales="free")
答案 0 :(得分:3)
您需要在摘要data.frame
中捕获您正在使用的变量。我们可以捕获组明智的最大值并将它们用于geom_segment()
和geom_text
的y位置:
library(tidyverse)
# get the max for each gear facet
df2 <- carData %>% group_by(gear) %>%
summarise(ypos = max(mpg)*1.1) %>%
mutate(x = lpos, xend = rpos) # use your factor level locators
p <- ggplot(carData, aes(cyl, mpg)) +
geom_boxplot() +
geom_segment(data = df2, aes(y = ypos, yend = ypos, x = x, xend = xend)) +
geom_text(data = df2, aes(y = ypos*1.02, x = mean(c(x, xend))), label = "3.0") +
facet_wrap( ~ gear,ncol=2, scales="free")
# if you want the end ticks
p + geom_segment(data = df2, aes(y = ypos, yend = ypos * .99, x = x, xend = x)) +
geom_segment(data = df2, aes(y = ypos, yend = ypos *.99, x = xend, xend = xend))