I am trying to create a faceted box plot within a function to do an exposure-response analysis on patient data. The plot is to be faceted by category, with exposure on the y-axis and a categorical response on the x-axis. I would also like to annotate the plot with the number of observations.
Some data:
set.seed(100)
dummy_data = data.frame(id = rep(1:50, each = 3),
expo = rnorm(50*3, mean = 50000, sd = 10000),
cat = rep(c("cat1", "cat2", "cat3"), times = 3, length.out = 50*3),
resp = sample(0:3, 50*3, replace = T))
outliers = data.frame(id = rep(51:60, each = 3),
expo = rnorm(10*3, mean = 300000, sd = 100000),
cat = rep(c("cat1", "cat2", "cat3"), times = 3, length.out = 10*3),
resp = 0)
dummy_data = rbind(dummy_data, outliers)
Here is my code so far:
boxplot_cat_er = function(data, exposure, response, cat, title = NULL, xlab = NULL, ylab = NULL) {
give.n <- function(x){
return(c(y = max(eval(substitute(exposure), data), na.rm = T), label = length(x)))
# experiment with the multiplier to find the perfect position
}
ggplot(data=data,
aes(x = as.factor(as.character({{response}})) , y = {{exposure}}))+
geom_boxplot(outlier.shape = NA) +
geom_jitter(width = 0.25) +
stat_summary(fun.data = give.n, geom = "text", color = "blue", fun.y = median, size=6) +
xlab(xlab)+
ylab(ylab)+
ggtitle(title) +
theme_bw() +
theme(axis.text.x=element_text(size=15),axis.text.y=element_text(size=15),
axis.title.y=element_text(size=15),axis.title.x=element_text(size=15),
legend.text=element_text(size=rel(1.2)), legend.title = element_text(size = rel(1.5)),
plot.title = element_text(size = 20)) +
facet_grid(as.formula(paste("~", paste(substitute(cat)))), scales = "free", space = "free") +
theme(strip.text.x = element_text(size = 15)) +
theme(plot.title = element_text(hjust = 0.5, vjust = 1))
}
I want it to look like this:
Everything works except the blue annotations. The issue seems to be with my custom give.n
function being passed to the stat_summary
function. When I run boxplot_cat_er(dummy_data, expo, resp, cat)
, I get the plot without the annotations and this error:
Evaluations still allude me in R. What am I doing wrong?