How to index x axis label label

I generated this graph below the script. enter image description here But how could I index β€œ10” in PM10, β€œ2” in SO2 and β€œ2” in NO2?

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

Can anyone help? Thank!

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
+4
source share
1 answer

You want to name the axis in the ggplot definitions. This is not possible in the place where you are doing it now, when you define a new name (as a string) for levels. Now what happens is that PM [10] will be recognized 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])))

Good luck.

Alexwhan :

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

.

+6

All Articles