如何创建自定义" geom_box"在ggplot2?

时间:2017-09-29 18:54:35

标签: r ggplot2 boxplot

我希望有一些类似于geom_boxplot的东西,但是它只有一个框,我可以设置框的下部和上部的功能,例如,显示加减1 SD平均数据。如果stat_boxplot可用于此目的,或者某些其他功能更适合,我不是。

这可以(几乎)使用stat =" identity"手动完成数据。和预先计算,例如:

y <- rnorm(100)
y1 <- mean(y) - sd(y)
y2 <- mean(y) + sd(y)
df1 <- data.frame(y)
df2 <- data.frame(
  x = 1,
  y0 = y1,
  y25 = y1,
  y50 = y1, # this is a problem...
  y75 = y2,
  y100 = y2
)

ggplot(df1, aes(x=1,y=y)) +
geom_boxplot() + 
  geom_boxplot(data = df2,
   mapping = aes(x = 1, y = 1, ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100),
   stat = "identity", alpha = 0.1, fill = "red")

enter image description here

这个例子有几个问题:

  1. 该框不是boxplot的宽度
  2. 盒子的下半部分比上半部分粗(因为我需要说明#34;中间&#34;应该在哪里)
  3. 计算需要每个数据手动进行(可以包含在一个函数中,但由于其他问题,我还没有达到目的)。
  4. 简而言之,我喜欢像geom_box这样的东西但是无法通过谷歌搜索找到它,我很乐意为某些方向如何继续编写这样的自定义geom函数(我猜this是一个开始,但欢迎一些更多的帮助。)

1 个答案:

答案 0 :(得分:1)

newbox <- function(values) {
  values <- na.omit(values)
  data.frame(
    ymin = mean(values) - sd(values),
    lower = mean(values) - sd(values),
    middle = mean(values),
    upper = mean(values) + sd(values),
    ymax = mean(values) + sd(values),
    width = 0.75
  )
}

ggplot(iris, aes(Species, Sepal.Length)) + 
  stat_summary(fun.data = newbox, geom = "boxplot", fatten = NA) 

enter image description here

喜欢那个?

如果你想要它没有填充,你可以使用内置函数,如:

ggplot(iris, aes(Species, Sepal.Length)) + 
  stat_summary(fun.data = mean_sdl, fun.args = list(mult = 1), 
               geom = "crossbar", fatten = NA)