如何在ggplot中添加多级x轴

时间:2016-03-30 08:14:46

标签: r ggplot2 axis

variable <-     c("PM10","SO2","NO","NO2","PM10","SO2","NO","NO2","PM10","SO2","NO","NO2","PM10","SO2","NO","NO2","PM10","SO2","NO","NO2","PM10","SO2","NO","NO2")
sex <- c("male","male","male","male","female","female","female","female",
     "male","male","male","male","female","female","female","female",
     "male","male","male","male","female","female","female","female")
exposureperiod <- c("P1","P1","P1","P1","P1","P1","P1","P1",
                "P2","P2","P2","P2","P2","P2","P2","P2",
                "P3","P3","P3","P3","P3","P3","P3","P3")

set.seed(100)
coef <- runif(24, -2, 2)
coef_lb <- coef - 0.3
coef_ub <- coef + 0.3

df <- data.frame(variable,sex,exposureperiod,coef,coef_lb,coef_ub)

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

df$exposureperiod <- factor(df$exposureperiod,levels=c("P1","P2","P3"))
df$sex <- factor(df$sex,levels=c("male","female"))

df <- df[order(df$variable,df$sex),]

df$aux <- c(1,2,3,
         5,6,7,
         11,12,13,
         15,16,17,
         21,22,23,
         25,26,27,
         31,32,33,
         35,36,37)

library(ggplot2)

plot <- ggplot(data = df, aes(x = aux, y = coef)) +
  geom_pointrange(aes(ymin=coef_lb,ymax=coef_ub),shape="none") +
  geom_point(aes(shape = exposureperiod)) +
  scale_shape_discrete(name  ="Exposure period",
                   breaks=c("P1", "P2","P3"),
                   labels=c("P1","P2","P3")) +
  scale_x_continuous("Sex and Pollutant",breaks=c(2,6,12,16,22,26,32,36), 
                 labels=c("Boys","Girls","Boys","Girls","Boys","Girls","Boys","Girls")) +
  scale_y_continuous("Mean Difference in Tanner Stage",
                 limits=c(-3, 3),
                 breaks=round(seq(-3, 3, by = 0.5),1)) +
  geom_hline(yintercept=0,alpha=1,linetype="dashed") +
  theme(axis.text.x = element_text()) +
  theme_bw(base_size = 16,base_family="Arial") +
  theme(legend.text.align = 0,
    legend.title = element_text(face="plain"),
    legend.key = element_blank(),
    legend.position = "bottom") +
  guides(shape= guide_legend(nrow = 3,byrow = TRUE)) +
  theme(text = element_text(colour = "black",face="plain"),
    axis.title.y = element_text(face="plain"),
    axis.title.x = element_text(face="plain"),
    axis.text.x = element_text(face="plain",hjust = 0),
    axis.text.y = element_text(face="plain")) + 
  theme(panel.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    axis.line = element_line(colour = "black"))+
  theme(axis.ticks = element_line(size = 1))

plot

通过上面的脚本,我得到了如下图表。

enter image description here

但是我想添加另一个级别的x轴,它表示PM10,SO2,NO和NO2,如下图所示。 (为了说明,我手动添加了这些污染物。)当然,x轴标题和图例应相应地向下移动。

我之前使用过facet,但我希望避免由facet产生的污染物之间的差距。

谢谢。

enter image description here

1 个答案:

答案 0 :(得分:0)

你可以试着面对情节

plot <- plot + facet_wrap(~variable)