Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206305

ggplot not drawing boxplots as expected

$
0
0

Consider the MWE below. I would like to generate boxplots with these ideas in mind:

  1. Food on the y-axix ordered according to Amot for Home, while Amt (1:40) on x-axis
  2. show mean points overlaying the boxes
  3. boxplots of Food to be ordered based on median of HomeSite from dfsummary data
  4. text annotations of N of observations (to be taken from dfsummary 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

enter image description here

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"

Viewing all articles
Browse latest Browse all 206305

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>