How to write chemical formulas in ggplot [duplicate]

血红的双手。 提交于 2021-01-27 12:00:48

问题


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?


回答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

Hope that works!




回答2:


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:

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:



来源:https://stackoverflow.com/questions/63902931/how-to-write-chemical-formulas-in-ggplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!