ggplot2中的自定义varwidth

use*_*010 5 r ggplot2

df = data.frame(a = c(0, 0), b = c(17, 15), 
                c = c(35,37), d = c(55,57), 
                e = c(80, 85), x = c(1, 2), 
                w1 = c(20, 30), w2 = c(0.2, 0.3))

ggplot(df) + 
  geom_boxplot(aes(x = x, ymin = a, lower = b, middle = c, upper = d, ymax = e),
               stat = "identity")
Run Code Online (Sandbox Code Playgroud)

我有一个数据框,包含箱图的每个分位数的值,(ae).是否可以使用列w1或w2来定义ggplot中箱线图的宽度?

我期望的结果是与使用varwidthgraphics::boxplot,但自定义的宽度.

graphics::boxplot(mpg~gear, mtcars, varwidth = T)
Run Code Online (Sandbox Code Playgroud)

不要认为这是重复的,因为看起来这个weight论点不起作用stat = identity.

use*_*010 2

看起来可以通过使用来完成stat_summary

df = data.frame(a = c(0, 0), b = c(17, 15), 
            c = c(35,37), d = c(55,57), 
            e = c(80, 85), x = factor(c(1, 2)), 
            w = c(0.2, 0.3))

df2 = reshape2::melt(data = df, id = "x")

ff = function(x){
  data.frame(
    ymin = x[1],
    lower = x[2],
    middle = x[3],
    upper = x[4],
    ymax = x[5],
    width = x[6]
  )
}

ggplot(df2, aes(x, value)) + stat_summary(fun.data = ff, geom = "boxplot") 
Run Code Online (Sandbox Code Playgroud)

但我不确定这是否是最好的方法。