Consider the MWE below. I would like to generate boxplots with these ideas in mind:
Food
on the y-axix ordered according toAmot
forHome
, whileAmt
(1:40) on x-axis- show mean points overlaying the boxes
- boxplots of
Food
to be ordered based on median ofHome
Site fromdfsummary
data - text annotations of
N
of observations (to be taken fromdfsummary
data)
MWE
df <- data.frame(
Site = sample(rep(c("Home", "Office"), size = 884)),
Food = sample(rep(c("Banana","Apple","Egg","Berry","Tomato","Potato","Bean","Pea","Nuts","Onion","Carrot","Cabbage","Eggplant"), size=884)),
Amt = sample(seq(1, 40, by = 0.25), size = 884, replace = TRUE)
)
random <- sample(seq(1, 884, by = 1), size = 100, replace = TRUE) # to randomly introduce 100 NAs to Amt vector
df$Amt[random] <- NA
Summary code
dfsummary <- df %>%
dplyr::group_by(Food, Site) %>%
dplyr::summarise(Median = round(median(Amt, na.rm=TRUE), digits=2), N = sum(!is.na(Amt))) %>%
ungroup()
ggplot code
p1 <- ggplot(df, aes(Amt, Food)) +
geom_boxplot() +
facet_grid(facets = . ~ Site)
Graph
I was expecting to see boxplots here.
Adding annotation
p2 <- p1 + geom_text(aes(y = 42, Food, label = paste("n=", N)), data = dfsummary, size = 3, nudge_x = 0.1) +
facet_grid(facets = . ~ Site)
Unfortunately, this doesn't work either.
Note
- tidyverse version is 1.3.0
- R version 3.6.2 (2019-12-12) -- "Dark and Stormy Night"