Add model parameters to plot diagrams, being parameters printed on multiple lines in italics, but their indices in regular font and in index
I want to add some estimated model parameters to facet plots, being parameters printed on multiple lines in italics, but their indices are in regular font and in index. Below is a minimal example:
library(ggplot2)
# Some fake parameter estimates
b1 <- c("2.33", "1.29", "1.15")
b2 <- c("4.45", "2.32", "2.28")
b3 <- c("2.30", "1.23", "2.10")
labs <- paste0("b1 = ", b1,
"\nb2 = ", b2, "\nb3 = ", b3)
dat <- data.frame(
x = rep(7, 3),
y = rep(41, 3),
drv = unique(mpg$drv),
labels = labs)
p <- ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(span = 0.8) +
theme_bw() +
facet_wrap(~drv) +
geom_text(data=dat,
aes(x,y,
label=labels),
hjust=1,
size = 3.6,
inherit.aes=FALSE)
p
In this graph, I needed to print the approximate parameters of the model as follows:
Can anyone please help? Thank you in advance.
source to share
In the code below, we use expressions plotmath
for italics and indexes. I don't know a way to include strings in expressions plotmath
, so I add each coefficient label separately with lapply
to run geom_text
three times. parse=TRUE
internally geom_text
ensures that expressions are plotmath
interpreted properly. I doubt this is the most elegant approach, but it works.
# Some fake parameter estimates
b1 <- c("2.33", "1.29", "1.15")
b2 <- c("4.45", "2.32", "2.28")
b3 <- c("2.30", "1.23", "2.10")
# Set up data frame of text coordinates
dat <- data.frame(
x = rep(5, 3),
y = rep(41, 3),
drv = unique(mpg$drv))
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(span = 0.8) +
theme_bw() +
facet_wrap(~ drv) +
# Add three lines of regression coefficients using lapply
lapply(1:3, function(i) {
dat = cbind(dat, lab=get(paste0("b",i))) # Add coefficient values to dat
dat$lab = paste0("italic(b)[",i,"] == ", dat$lab) # Add plotmath expression to get italics and subscript
dat$y = dat$y - 1.6*(i - 1) # Set vertical position of each coefficient label
geom_text(data=dat, aes(x, y, label=lab), hjust=0,
size = 3.6, parse=TRUE, inherit.aes=FALSE)
})
source to share