Add secondary X axis labels to ggplot with one X axis

后端 未结 3 1673
囚心锁ツ
囚心锁ツ 2020-12-03 16:16

**Edit, there are two great solutions here, one is marked as the answer, but @hrbrmstr provides a great solution combining two ggplots which works well for this simple plot.

3条回答
  •  我在风中等你
    2020-12-03 17:07

    I wrote all labels as major-labels.

    # OP's
    breaks.major <- c(0,15,37.5,52.5,67.5,82.5,95,100) #defines the midpoints of the categories (label locations)
    breaks.minor <- c(30,45,60,75,90) #defines the edges of the categories (second label set I need)
    labels.minor <- c("","Extremely \nDissatisfied","Dissatisfied","Uncertain","Satisfied","Very \nSatisfied","Extremely \nSatisfied","")
    lims =c(0,100)
    
    breaks.major2 <- c(0,15,37.5,52.5,67.5,82.5,95)
    breaks.minor2 <- c(30,45,60,75,90,100)       # put 100 into minor from major
    
    breaks.comb <- sort(c(breaks.major2, breaks.minor2 - 1.0E-6))  # avoid the just same value as minor
    label.comb <- c(0, "\nExtremely \nDissatisfied", 30, "\nDissatisfied", 45, "\nUncertain", 60, 
                    "\nSatisfied", 75, "\nVery \nSatisfied", 90, "\nExtremely \nSatisfied", 100)
    
    library(ggplot2)
    g <- ggplot(mpg, aes(class))+
      geom_bar()+
      coord_flip()+
      scale_y_continuous(limit = lims, minor_breaks = breaks.minor2, breaks = breaks.comb, 
                         labels = label.comb, expand = c(0,0)) +
      theme(panel.grid.major.x = element_blank()) +
      theme(panel.grid.major.y = element_blank()) +
      theme(axis.ticks.x=element_blank()) +
      theme(axis.title= element_blank()) +
      theme(plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "lines"))
    

提交回复
热议问题