0

I would just like to simply add an annotation to my ggplot with the exponential function on it like this graph: excel graph

Here is the data:Data

Here is the code I used thus far:

dfplot<-ggplot(data, aes(dilution.factor,Concentation)) + 
geom_point(size=3)+ geom_smooth(method="auto",se=FALSE, colour="black")+
scale_y_continuous(breaks=seq(0,14,by=2))

dfplot2<-dfplot+labs(x=('Dilution Factor'), y=expression('Concentration' ~ 
(ng/mu*L)))+
theme_bw() + theme(panel.border = element_blank(),
                 panel.grid.major = element_blank(),
                 panel.grid.minor = element_blank(),
                 axis.text = element_text(colour="black"), 
                 axis.line = element_line(colour = "black"))

dfplot3<- dfplot2+annotate("text", x=3, y=10, label = "R^2 == 1",parse=TRUE)
dfplot3
dfplot4<-dfplot3+annotate("text", x=3, y=11, label = 
as.character(expression("y=13.048e^-{0.697x}" ,parse=TRUE)))
dfplot4

I can get all the way up to putting the r^2 value (dfplot3)dfplot3 For some reason I cannot get it to add the exponential equation in. I keep getting this error: Error: Aesthetics must be either length 1 or the same as the data (1): label

What am i doing wrong?

1 Answers1

2

Not quite sure about the as.character(expression()) syntax you are using, but when you are parsing annotation text, ggplot2 doesn't understand the 'human' style notation shortcut of placing a number next to a letter 13.084e, you need to tell it explicitly this is multiplication. You also need == instead of =.

annotate("text", x=3, y=11, label = "y == 13.048*e^-{0.697*x}", parse =TRUE)

enter image description here

Edit: I see that you have included parse = TRUE inside the expression call, I think this is a mistake. To do it with expression you would write the following, but this is not in fact necessary:

annotate("text", x=3, y=11, label = as.character(expression("y == 13.048*e^-{0.697*x}")), parse = T)
gatsky
  • 1,180
  • 7
  • 8
  • Nice answer! Can you explain about `*` part? – pogibas Feb 04 '18 at 06:09
  • 1
    If you take a look at the ggplot2 source code (https://github.com/tidyverse/ggplot2/blob/master/R/geom-text.r), you will see that if parse = TRUE in `annotate` or `geom_text` calls, the label text is fed into the `parse` function simply as `parse(text = your_label)`. The syntax for writing mathematical expressions can be seen at `?grDevices::plotmath`. – gatsky Feb 04 '18 at 06:21