如何下标x轴刻度标签 [英] how to subscript the x axis tick label
问题描述
我使用以下脚本生成了该图. 但是,如何在PM10中标上"10",在SO2中标下"2",而在NO2中标下"2"呢?
I generated this graph with the below script. But how could I subscript the "10" in PM10, "2" in SO2, and"2" in NO2?
我尝试了levels(df$variable) <- c("PM[10]","SO[2]", "NO", "NO[2]")
,但是不起作用.
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
推荐答案
您要在ggplot定义中命名轴.在现在要为关卡定义新名称(作为字符串)的位置,这是不可能的.现在发生的是,PM [10]将被识别并读取为字符串.
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.
将此添加到您的ggplot脚本中.这将您具有的x轴刻度线定义为离散刻度:
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])))
玩得开心.
感谢 Alexwhan ,它也可以写为:
+ scale_x_discrete("Air pollutant", labels = parse(text = levels(df$variable)))
哪个更容易.
这篇关于如何下标x轴刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!