Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a complex label with italics and a variable to ggplot?

I have read many postings on this topic using expression(), paste(), and bquote(), or some combination. I think I am close to solving my problem, but I just can't get there. The following script generates a plot labelled with "y = 1 + 2(x); r^2= 0.9". How can I italicize "y" and "x", and italicize the "r" and superscript the 2 of "r^2"? If I have overlooked a relevant earlier post, sorry, but please direct me to it.

df <- data.frame(x=c(1:5), y=c(1:5))
a <- 1    
b <- 2
r2 <- 0.9
eq <- paste("y = ", a, " + ", b, "(x); r^2=", r2)
ggplot(data=df, aes(x=x, y=y))+
  geom_point(color="black")+
  geom_text(x=2, y=4,label=eq, parse=FALSE)
like image 605
JPollock Avatar asked Dec 04 '18 20:12

JPollock


People also ask

How do you italicize labels in ggplot2?

In ggplot2, we have a function scale_x_discrete that can be used to change the default font to italic using expression function.

How do I change data labels in ggplot2?

Changing axis labels To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code. Note: You can also use +labs(title = "Title") which is equivalent to ggtitle .


1 Answers

You could use annotate() which allows you to paste directly into the plot.

library(ggplot2)
ggplot(data=df, aes(x=x, y=y)) +
  geom_point(color="black") +
  annotate('text', 2.5, 4, 
           label=paste("italic(y)==", a, "+", b, 
                       "~italic(x)~';'~italic(r)^2==", r2), 
           parse=TRUE, 
           hjust=1, size=5)

Yields:

enter image description here

Data:

df <- data.frame(x=c(1:5), y=c(1:5))
a <- 1
b <- 2
r2 <- 0.9
like image 61
jay.sf Avatar answered Nov 10 '22 08:11

jay.sf