How to write chemical formulas in ggplot

Viewed 545

I need to plot some data and one of the plot has to have the sulphate formula (SO42-) in the labels.

I am using this code

a=c(1,2,3,4,5)
b=c(1,2,3,4,5)
dd=data.frame(a,b)

G<-ggplot(dd)+
geom_line(x=a, y=b, color="blue")+
labs(x="Depth (m)", y=expression("nss SO"[4]^{2-}"(ppb)"))
G

And, of course, it doesn't work: either the - is written as a dash between the 2 and the ppb or it simply does nothing after giving me a wall of text. Am I missing something?

2 Answers

First, you're missing the aes() component of geom_line. For the expression, you're not quite hitting the syntax correctly. Using information found here, I was able to create....

library(ggplot2)
a=c(1,2,3,4,5)
b=c(1,2,3,4,5)
dd=data.frame(a,b)

G <-ggplot(dd)+
  geom_line(aes(x=a, y=b), color = 'blue') + # need to include aes() designation here
  labs(x="Depth (m)", y=expression("nss SO" ["4"] ^"2-"*" (ppb)"))
G

enter image description here

Hope that works!

Try this also:

#Data
a=c(1,2,3,4,5)
b=c(1,2,3,4,5)
dd=data.frame(a,b)
#Code
G<-ggplot(dd,aes(x=a, y=b))+
  geom_line(color="blue")+
  labs(x="Depth (m)", y=expression(nss~SO[4]^{2^{"-"}}~(ppb)))
G

Output:

enter image description here

Or this (deeply sorry for my knowledge of chemistry formulas):

#Code 2
G<-ggplot(dd,aes(x=a, y=b))+
  geom_line(color="blue")+
  labs(x="Depth (m)", y=expression(nss~SO[4]^{"2-"}~(ppb)))
G

Output:

enter image description here

Related