r - 使用 ggplot_build () 手动设置后,如何在 ggplot 箱形图中自定义凹口?

标签 r ggplot2

我有一个与 this one 相关的问题关于如何在 ggplot boxplot 中自定义凹口。问题的作者回复了自己,并用 ggplot_build() 给出了提示,但不幸的是我无法使用它。

所以我的问题是:一旦您使用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

我做错了什么? 非常感谢

最佳答案

使用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

关于r - 使用 ggplot_build () 手动设置后,如何在 ggplot 箱形图中自定义凹口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43388034/

相关文章:

r - 如何根据向量值在点图中使用不同的符号

r - 可以通过[.data.table()中的浏览器查看.SD吗?

r - 如何使用 R tidymodels 工作流程在没有截距的情况下拟合模型?

r - 将 ggplot2 与 R : Looks and Syntax 中的基本图相结合

r - ggplot 两个阴影区域 geom_area

r - 从预处理的表达式矩阵创建 eset 对象?

r - R-Server或Shiny Server是否为每个用户创建一个新的R进程/实例?

r - 如何手动向ggplot添加图例? -R

r - 根据ggplot中的第三个因素为线图着色

r - 为什么 geom_boxplot() 没有输出?