user8542010
user8542010

Reputation: 113

custom varwidth in 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")

I have a dataframe containing the values of each quantile for a boxplot, (a-e). Is it possible use columns w1 or w2 to define the width of the boxplots in ggplot?

My desired result is similar to using varwidth in graphics::boxplot but with custom widths.

graphics::boxplot(mpg~gear, mtcars, varwidth = T)

Don't think this is a duplicate since it seems like the weight argument doesn't work with stat = identity.

Upvotes: 5

Views: 365

Answers (1)

user8542010
user8542010

Reputation: 113

Looks like it can be done by using 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") 

But i am not sure if this is the best way to do it.

Upvotes: 2

Related Questions