简体   繁体   中英

Boxplot with ggplot2

I am working on a boxplot with forecast and observations which is quite long dataset. I am providing a sample format here.

> forecasts <- data.frame(f_type = c(rep("A", 9), rep("B", 9)), 
                          Date = c(rep(as.Date("2007-01-31"),3), rep(as.Date("2007-02-28"), 3), rep(as.Date("2007-03-31"), 3), rep(as.Date("2007-01-31"), 3), rep(as.Date("2007-02-28"), 3), rep(as.Date("2007-03-31"), 3)), 
                          value = c(10, 50, 60, 05, 90, 20, 30, 46, 39, 69, 82, 48, 65, 99, 75, 15 ,49, 27))
> 
> observation <- data.frame(Dt = c(as.Date("2007-01-31"), as.Date("2007-02-28"), as.Date("2007-03-31")), 
                            obs = c(30,49,57))

So far I have:

ggplot() + 
    geom_boxplot(data = forecasts,
                 aes(x = as.factor(Date), y = value, 
                     group = interaction(Date, f_type), fill = f_type)) +  
    geom_line(data = observations,
              aes(x = as.factor(Dt), y = obs, group = 1), 
              size = 2)

With this the box and whiskers are set by default. I want to assign these values so that I will know the extent of the whiskers. I have tried to pass a function with stat_summary with like:

f <- function(x) {
    r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))
    names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
    r
}

o <- function(x) {
    subset(x, x < quantile(x,probs = 0.05) | quantile(x,probs = 0.95) < x)
}

ggplot(forecasts, aes(x = as.factor(Date), y = value)) + 
    stat_summary(fun.data = f, geom = "boxplot", aes(group = interaction(Date, f_type), fill = f_type)) +
    stat_summary(fun.y = o, geom = "point") 

But, with this the groups are messed up. This produces stacked up plots. Does anyone how to accomplish this?

With a little preprocessing you can summarise the values by date and f_type to generate the desired ymin , lower , middle , upper and ymax arguments of geom_boxplot (the trick is to set stat = "identity" ):

forecasts %>% group_by(f_type, Date) %>% 
    summarise( # You can set your desired values/quantiles here
        y_min = quantile(value, 0.05),
        low = quantile(value, 0.25),
        mid = quantile(value, 0.5),
        high = quantile(value, 0.75),
        y_max = quantile(value, 0.95)
    ) %>% 
    ggplot() + 
    geom_boxplot(
        aes(
            ymin = y_min,
            lower = low,
            middle = mid,
            upper = high,
            ymax = y_max,
            x = as.factor(Date),
            fill = f_type
        ), 
        stat = "identity"
    ) + 
    geom_line(
        data = observations,
        aes(
            x = as.factor(Dt), 
            y = obs, group = 1
        ), 
        size = 2
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM