Can I use markup in a ggplot annotation?
Let's say, I have this graph:
p <- function(i) 8*i
a <- function(i) 1+4*i*(i-1)
library(ggplot2)
library(reshape2)
i <- 1:(8*365/7)
d <- data.frame(i=i,p=p(i),a=sapply(i,a))
d <- melt(d, id.vars='i')
p <- ggplot(d, aes(i, value, linetype=variable)) +
geom_hline(yintercept=700^2) +
geom_line() +
scale_linetype_manual(values=c(2,1)) +
#geom_point() +
scale_x_continuous(breaks=(0:20)*365/7, labels=0:20) +
#scale_y_continuous(breaks=c(0,700^2), labels=c(0,expression(L^2)))
scale_y_sqrt() +
#scale_y_log10() +
annotate('text', 8*365/7, 1e3, label="P(i)=8i", hjust=1, size=3) +
annotate('text', 8*365/7, 2.5e5, label="A(i)=1+4i(i-1)", hjust=1, size=3)
print(p + theme_classic())
I know I can use fontface=3 and put everything in italic. But I do not want the numbers in italic, only the variable i
. Preferably, P
and A
would not be in italic as well.
Any ideas?
To write text in italic font, use a single underscore or asterix before and after the text. To write text in bold font, use a double asterix or underscores before and after the text.
The annotate() function allows to add all kind of shape on a ggplot2 chart. The first argument will control what kind is used: rect or segment for rectangle, segment or arrow.
You can use the annotate() function to add text to plots in ggplot2. where: x, y: The (x, y) coordinates where the text should be placed. label: The text to display.
Right now this page is the top search result on google for ggplot annotate italic. For the benefit of those who simply want to italicize an entire annotation, I'm writing this post. Use annotate's fontface
option. Example:
seq(0,3.14,0.01)
qplot(x, sin(x)) + # works the same for qplot or ggplot
annotate(geom = 'text',
x = 1.5,
y = 0.5,
hjust = 0.5,
label = 'Hello, World',
fontface = 'italic')
Use parse=TRUE
and supply a string formatted according to ?plotmath
.
p <- ggplot(d, aes(i, value, linetype=variable)) +
geom_hline(yintercept=700^2) +
geom_line() +
scale_linetype_manual(values=c(2,1)) +
scale_x_continuous(breaks=(0:20)*365/7, labels=0:20) +
scale_y_sqrt() +
annotate('text', 8*365/7, 1e3,
label="P(italic(i))==8~italic(i)", parse=TRUE,
hjust=1, size=3) +
annotate('text', 8*365/7, 2.5e5,
label="A(italic(i))==1+4~italic(i)(italic(i)-1)", parse=TRUE,
hjust=1, size=3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With