简体   繁体   中英

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? Ie 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"))

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") )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM