3

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?

Raffaello Nardin
  • 151
  • 2
  • 11

2 Answers2

1

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!

TTS
  • 1,818
  • 7
  • 16
  • Thanks! Yes, now it does work... the role of the * is just to add a space if I understand it correctly? – Raffaello Nardin Sep 17 '20 at 08:35
  • The page says "* Acts as a connector, this allows you to join several element." I actually tried to create an offset between the sub/superscripts but wasn't able to. – TTS Sep 17 '20 at 19:23
1

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

Duck
  • 39,058
  • 13
  • 42
  • 84