Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

r - how to subscript the x axis tick label

I generated this graph with the below script. enter image description here But how could I subscript the "10" in PM10, "2" in SO2, and"2" in NO2?

I tried levels(df$variable) <- c("PM[10]","SO[2]", "NO", "NO[2]"), but does not work.

Can anyone help? Thank you!

variable <- c("PM10","SO2","NO","NO2")
coef <- c(10,20,30,40)
coef_lb <- c(-5,10,23,27)
coef_ub <- c(20,39,39,50)

df <- as.data.frame(cbind(variable, as.numeric(coef),as.numeric(coef_lb),as.numeric(coef_ub)))


df$variable <- factor(df$variable,levels=c("PM10","SO2","NO","NO2"))
levels(df$variable) <- c("PM[10]","SO[2]", "NO", "NO[2]")

library(ggplot2)
#ggplot 95%CI
BWplot <- ggplot(data=df,aes(x=variable,y=coef))
BWplot <- BWplot + geom_pointrange(aes(ymin=coef_lb,ymax=coef_ub))
BWplot <- BWplot + geom_point() 
BWplot <- BWplot + scale_y_continuous(limits=c(-110, 110),breaks=seq(-100, 100, by = 20))
BWplot <- BWplot + xlab("Air pollutant") 
BWplot <- BWplot + ylab("Mean change") 
BWplot <- BWplot + geom_hline(yintercept=0,alpha=0.5)
BWplot
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want to name the axis in the ggplot definitions. This is not possible at the position where you do it now where you are defining a new name (as a string) for the levels. What happens now is that PM[10] will be recognised and read as a string.

Add this to your ggplot script. This defines the x-axis ticks that you have as a discrete scale:

+ scale_x_discrete("Air pollutant", labels = c(expression(PM[10]),expression(SO[2]), expression(NO), expression(NO[2])))

Have fun.

With thanks to Alexwhan it can also be written as:

+ scale_x_discrete("Air pollutant", labels = parse(text = levels(df$variable)))

Which is even easier.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...