Search code examples
rggplot2axis-labels

ggplot change x-axis labels without changing underlying data


I am plotting with facets and discrete data on the x-axis. How can I change the x-axis labels without changing the underlying data? I.e. instead of labels reading "a","b","c","d" they should read "Lab 1","Lab 2","Lab 3","Lab 4".

df <- data.frame(x = factor(rep(c("a","b","c","d"),4), levels = c("a","b","c","d")),
                 y = rep(seq(1,8,1),2),
                 z = c(rep("x",4),rep("y",4)),
                 facet = rep(c(rep("1",2),rep("2",2)),4))


ggplot(NULL) +
  geom_line(data=df, aes(y=y, x=x, linetype=z, group = z, colour=z)) +
  facet_grid(~facet, scales="free_x", space="free_x") +
  scale_colour_manual(values=c("Red","Blue")) +
  scale_linetype_manual(values=c("solid", "dashed"))

Solution

  • You can use a named character vector for the labels argument in scale_x_discrete.

    scale_x_discrete(labels = c("a" = "Lab 1", "b" =  "Lab 2", "c" = "Lab 3", "d" = "Lab 4") )
    

    Alternatively, you could give both breaks and labels

    scale_x_discrete(breaks = c("a", "b", "c", "d"), 
                     labels = c("Lab 1", "Lab 2", "Lab 3", "Lab 4") )