Search code examples
rggplot2x-axis

Add second x-axis to ggplot


I build this plot:

df_ebf <- df_ebf %>%
  map_df(rev)

labels.minor <- c("nie","selten","manchmal", "mehrmals", "oft", "sehr oft", "immerzu")

ggplot(data=df_ebf, aes(x=forcats::fct_inorder(Skalen), y=Werte, group="")) +
  geom_line(color = "#003560") +
  geom_point(color = "#003560") +
  coord_flip() +
  labs(x="EBF-Skalen") +
  scale_y_continuous(limits = c(0, 6), breaks = c(0,1,2,3,4,5,6), sec.axis = dup_axis(),expand = c(0,0)) +
  scale_x_discrete(expand = c(0,0)) +
  theme(panel.grid.major.y = element_blank(),panel.grid.minor.x = element_blank(),axis.line.x = element_line(size = 1, colour = "black", linetype=1),axis.title=element_blank())

enter image description here

Now I want to add a second x-axis below the lower x-axis with the labels.minor.

I found this and this when looking for a solution in the forum, but it didn't work for my case.


Solution

  • If your labels.minor are at the exact position of the breaks, you can simply paste together the labels with a newline character. Example below:

    library(ggplot2)
    
    df <- data.frame(
      x = runif(10, min = 0, max = 6),
      y = letters[1:10]
    )
    
    labels.minor <- c("nie","selten","manchmal", "mehrmals", "oft", "sehr oft", "immerzu")
    
    ggplot(df, aes(x, y)) +
      geom_path(aes(group = -1)) +
      geom_point() +
      scale_x_continuous(limits = c(0, 6), breaks = 0:6,
                         labels = paste0(0:6, "\n", labels.minor),
                         sec.axis = sec_axis(~.x, breaks = 0:6))
    

    Created on 2021-04-10 by the reprex package (v1.0.0)