Hi,
I'm sure there must be a simple solution to this. I'm forever getting hung up on legends of mixed plots. I'm hoping @mara will come to my rescue again.
I have model outcomes - two models, summaries of annual predictions for each - which I display as boxplots within year; and annual observations for the first years - which I display using geom_step.
If you look at the following reprex (made up data, and some stuff omitted) I have the observations in a separate column and use the var
factor to control fill and colour.
So the structure of the graph looks fine, but in the legend I would like to get a line for the observed, rather than a boxplot symbol. Is this possible?
I tried playing with key_glyph, but couldn't seem to get it do the job.
I'm happy to rejig my data into another layout, if necessary, but my colleagues and I are set on this boxplot and step type of graphic.
A secondary question, in TBL you may notice that the last observation (2002) is repeated for 2003 to force the step to span 2002. Is there a more elegant way to do this?
Any other comments on my plotting code welcomed.
Thanks for your help,
Ron.
library(tidyverse)
TBL <- structure(list(model = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, NA, NA, NA, NA), .Label = c("with", "without"), class = "factor"),
med = c(10, 9, 8, 7, 6, 11, 10, 9, 8, 7, NA, NA, NA, NA),
year = structure(c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L,
1L, 2L, 3L, 4L), .Label = c("2000", "2001", "2002", "2003",
"2004"), class = "factor"), bot = c(5, 4, 3, 2, 1, 6, 5,
4, 3, 2, NA, NA, NA, NA), low = c(8.5, 7.5, 6.5, 5.5, 4.5,
9.5, 8.5, 7.5, 6.5, 5.5, NA, NA, NA, NA), upp = c(11.5, 10.5,
9.5, 8.5, 7.5, 12.5, 11.5, 10.5, 9.5, 8.5, NA, NA, NA, NA
), top = c(15, 14, 13, 12, 11, 16, 15, 14, 13, 12, NA, NA,
NA, NA), obs = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
12, 8, 10, 10), var = structure(c(2L, 2L, 2L, 2L, 2L, 3L,
3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L), .Label = c("obs", "with",
"without"), class = "factor")), row.names = c(NA, -14L), class = c("tbl_df",
"tbl", "data.frame"))
pp <- ggplot() +
geom_boxplot(data = TBL %>% filter(is.na(obs)),
aes(x = year, ymin = bot, lower = low, middle = med, upper = upp, ymax = top,
group = year:model, fill = var, colour = var), alpha = 0.5, stat = 'identity') +
geom_step(data = TBL, aes(x = as.numeric(year)-0.5, y = obs, colour = var, fill = var)) +
scale_fill_manual(values = c('with' = 'purple','without' = 'red', 'obs' = NA)) +
scale_colour_manual(values = c('with' = 'purple', 'without' = 'red', 'obs' = 'black'))
#> Warning: Ignoring unknown aesthetics: fill
print(pp)
#> Warning: Removed 10 row(s) containing missing values (geom_path).
Created on 2020-08-24 by the reprex package (v0.3.0)