基于这个答案 https://stackoverflow.com/a/32281523,
library(grid)
library(ggplot2)
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_line() +
labs(caption= "First~line \n italic('and a second,')~bold('fancy one') \n
'also,'~integral(f(x)*dx, a, b)~'for good measure'")+
(theme_grey() %+replace% theme(plot.caption = element_custom()))
element_custom <- function() {
structure(list(), class = c("element_custom", "element_text"))
}
element_grob.element_custom <- function(element, label="", ...) {
disect <- strsplit(label, "\\n")[[1]]
labels <- lapply(disect, function(x) tryCatch(parse(text=x),
error = function(e) x))
hl <- unit(rep(1, length(labels)), 'strheight', data=labels) + unit(0.1,"line")
yl <- c(list(unit(0,"line")),
lapply(seq_along(labels[-length(labels)]), function(ii) sum(hl[1:ii])))
cl <- do.call(gList, Map(function(label, ii)
textGrob(label, y = unit(1,"npc")-yl[[ii]], hjust=0, x=0, vjust=1),
label = labels, ii = seq_along(labels)))
gTree(children = cl, cl="sl", heights = hl, gp=gpar(col="grey50",fontsize=8))
}
heightDetails.sl <- function(x) sum(x$heights)