2017-09-11 3 views
0

ファセットグループに応じて各geom_lineの高さを調整するには(y-limはグループによって異なります、下の画像を参照)ggplot2のファセットに有意線を追加

各条件の高さを含むカスタムdata.frameを作成しようとしましたが、これはgeom_lineで受け付けられません。

私は、この小さな作業例があります:あなたはあなたの概要data.frameに、とのファセットに使用している変数をキャプチャする必要が

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

+0

あなたは別の面で異なるレベルの 'data.frame'を試してみましたことを言うが、 'df1'はそれを持っていません。あなたは実際に異なるレベルのものを表示できますか? – Axeman

答えて

2

を。私たちは、グループごとの最大値をキャプチャし、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

関連する問題