ggplot中x轴下方的表格

Hello everyone I was trying to add some text below the x axis in ggplot2 and I was able to do so using geom_textand with help of coord_cartesian but I couldn't make it reproducible as this need to run in a loop. I thought that adding the values I want with the row names (First, Second) in a table would fix it, does anybody have experience in that. below is the workaround I did. Thank you very much in advance.


## Data

Grade <- 1 : 20 

Case <-  rep(paste('case' , 1:5,sep = ''),4)

Number <- paste('n', 1:20 ,  sep = '')

Class <- c(rep('Class1',5) , rep('Class2',5) , rep('Class3',5) , rep('Class4',5))

se <- 0.2

df <- data.frame(Grade,Case ,Number, Class  , se)


## plot 

ggplot(df, aes(x= factor(Case , levels = c('case1','case2' , 'case3' , 'case4','case5')) , y=Grade ,
                        fill= Grade)) + 


  geom_bar(position="dodge", stat="identity",
           colour="black",
           size=.4) +    

  geom_errorbar(aes(ymin=Grade +se, ymax=Grade +se),
                size=.3,    
                width=.2,
                position=position_dodge(.9))+


  geom_linerange(aes(ymin = Grade , ymax = Grade +se),position=position_dodge(.9))+

  geom_text(aes(label=Number , y = Grade  + se + 1),data=df, position=position_dodge(0.9), size= 4) +


  ggtitle('Place a table below x axis')+

  facet_grid(~Class) + 

  xlab('') + 

  ylab('Case Num') + 

  theme_gray()+


  theme(plot.margin = unit(c(1,1,1,6), "lines"),
        axis.text.x = element_text(size = 15))  +

  scale_x_discrete(labels = paste(1:5 , '\n' ,  10:15,  sep = '')) + 

  geom_text(data = df[df$Class == 'Class1',],x = -1 , y = -3, 

            label= 'First\nSecond' , size = 4)+


  coord_cartesian(clip = "off" , xlim = c(1, 5) )

enter image description here

评论