在ggplot2中为facet添加重要性行

时间:2017-09-11 12:45:08

标签: r ggplot2 boxplot

如何根据构面组调整每个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")

enter image description here

1 个答案:

答案 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))

enter image description here