2017-05-14 5 views
2

Ich arbeite an einem Boxplot mit Vorhersage und Beobachtungen, was ein ziemlich langer Datensatz ist. Ich stelle hier ein Beispielformat zur Verfügung.Boxplot mit ggplot2

> 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)) 

Bisher habe ich:

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) 

dieser mit der Box und Whisker sind standardmäßig eingestellt. Ich möchte diese Werte so zuweisen, dass ich das Ausmaß der Barthaare kenne. Ich habe versucht, eine Funktion mit stat_summary mit Gleichem passieren:

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") 

Aber mit dieser die Gruppen durcheinander. Dies erzeugt gestapelte Plots. Kann jemand das erreichen?

Antwort

4

Mit ein wenig Vorverarbeitung können Sie die Werte nach dem Datum zusammenfassen und f_type die gewünschten ymin zu erzeugen, lower, middle, upper und ymax Argumente von geom_boxplot (der Trick stat = "identity" gesetzt ist):

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 
    ) 
Verwandte Themen