I am annotating my graph with summary statistics. I'd like to use a bold font to quickly draw the user's eyes to the best/worst statistics by group. The highlighted numbers would need to be determined at run-time by the data itself.
Here's an example using the ChickWeight dataset, showing changes in chick weights based on their diet:
library(ggplot2)
library(dplyr)
# Calculate end vs start weights
df <- merge(filter(ChickWeight, Time==21), filter(ChickWeight, Time==0), by=c("Chick", "Diet"))
df$dWeight <- df$weight.x - df$weight.y
# Summary statistics: sd & mean
df.stat <- do.call(data.frame,
aggregate(dWeight ~ Diet,
data=df,
FUN = function(x) c(SD=sd(x), MN=mean(x))))
ggplot(data = df) +
facet_grid(Diet ~ .) +
geom_histogram(binwidth=10, aes(x=dWeight)) +
geom_vline(data=df.stat, aes(xintercept = dWeight.MN), color="black") +
geom_text(data=df.stat, aes(x=Inf,
y=Inf,
label = sprintf("\nmean = %4.1f\nsd = %4.1f",
dWeight.MN, dWeight.SD),
hjust=1,
vjust=1))
In the graph below, I would want to only highlight the following text:
In group 3, "mean = 229.5" would become "mean = 229.5"
In group 4, "sd = 43.9" would become "sd = 43.9"