Home > Mobile >  ggplot2: Modifying all but first axis labels via a function
ggplot2: Modifying all but first axis labels via a function

Time:11-01

I have a plot with an numeric x axis. The values are years. I want to modify the labels so that the first year is displayed in full, the subsequent instances are abbreviated. With this in mind, I wrote a function which replaces the first two digits. It works when applying it to a vector, however, not when using it in ggplot. Any idea what I am missing? Many thanks.

PS I am aware of the scales package and its related functions for date/time scales. I have also seen this SO enter image description here

CodePudding user response:

Here is a solution in case you do not want to set the first value manually.

df %>%
  ggplot()  
  geom_bar(aes(x = seq_year, 
               y = values),
           stat="identity") 
  scale_x_continuous(label=function(x) 
    c(x[1:2], str_replace(x[3:length(x)], regex("\\d{2}"), "'")))
  • Related