2017-04-13 20 views
3

我有一個相對於this one有關如何在ggplot boxplot中自定義凹槽的問題。這個問題的作者回復自己並給了ggplot_build()暗示,但我很遺憾不能使用它。如何使用ggplot_build()手動設置ggplot box plot中的凹槽?

所以我的問題是:一旦你手動設置缺口限額與ggplot_build(),怎麼一個重複使用它來定製自己的箱線圖?

這裏是我的數據

vib = c(3.94,-0.61,0.03,0.46) 
pla = c(0.784444444, 1.11,-1.98,-1.39) 

df = data.frame(value = c(vib, pla), 
       group = c(rep("vibration", times = 4), rep("placebo", times = 4))) 

p <- ggplot(df, aes(x = group, y = value)) + geom_boxplot(notch=TRUE) 

gg <- ggplot_build(p) 

gg$data[[1]]$notchlower[1]<-sort(vib)[qbinom(c(.25, .975), length(vib), .5)][1] 
gg$data[[1]]$notchlower[2]<-sort(pla)[qbinom(c(.25, .975), length(pla), .5)][1] 

gg$data[[1]]$notchupper[1]<-sort(vib)[qbinom(c(.25, .975), length(vib), .5)][2] 
gg$data[[1]]$notchupper[2]<-sort(pla)[qbinom(c(.25, .975), length(pla), .5)][2] 

gg$data[[1]] 

ggplot(gg$data[[1]], aes(x = x)) + 
    geom_boxplot(aes(ymin = ymin, lower = lower, middle = middle, upper = upper, ymax = ymax), 
      stat = "identity", 
      notch = TRUE) 

並將得到警告信息

Error in ifelse(notch, data$notchlower, NA) : replacement has length zero 
In addition: Warning message: 
In rep(yes, length.out = length(ans)) : 
    'x' is NULL so the result will be NULL 

我在做什麼錯? 非常感謝

+0

@beetroot哪裏是我的代碼的問題? – Epifunky

回答

2

使用ggplot_gtable扭轉操作,而不是再次饋入ggplot

gg$data[[1]]$notchlower[1:2]<- c(-1,0) 
gg$data[[1]]$notchupper[1:2]<- c(0.5, 1) 

plot(ggplot_gtable(gg)) 

enter image description here