0

My x-axis is time format: "2001-01-01, 2001-02-01..." How to show the axis with years only? I think scale_x_discrete is the function that I need to use, but I don't know how to describe the breaks.

Phil
  • 7,287
  • 3
  • 36
  • 66
Shirley zou
  • 31
  • 1
  • 3
  • 1
    It will be better to use `scale_x_date`. Please provide a reproducible example of your data and code you have try so far (see: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – dc37 Mar 19 '20 at 03:56
  • 1
    Check that your x-axis is Date type, something like `class(df$date)`. By default, ggplot usually only displays the year when the x axis is date type, so your question makes me suspect your x axis is character. `scale_x_date` only works with date type. – astrofunkswag Mar 19 '20 at 04:05

2 Answers2

0

You can use the labels= parameter to provide a function that will format your dates the way you want.

  scale_x_date(labels = scales::date_format("%Y"))
user2332849
  • 1,421
  • 1
  • 9
  • 12
0

Alternatively to the use of format function from scales package, you can use date_breaks and date_labels arguments of scale_x_date function.

Here, I show you an example using lubridate package to make the date sequence. You have to be sure that your date column is actually in a date format as pointed out by @astrofunkswag.

library(lubridate)
df <- data.frame(date = seq(ymd("2001-01-01"), ymd("2005-12-01"), by = "month"),
                 value = rnorm(60))

str(df)
'data.frame':   60 obs. of  2 variables:
 $ date : Date, format: "2001-01-01" "2001-02-01" "2001-03-01" "2001-04-01" ...
 $ value: num  0.2839 -0.9031 -0.2851 0.0107 -0.1647 ...


library(ggplot2)
ggplot(df, aes(x = date, y = value))+
  geom_line()+
  scale_x_date(date_breaks = "year", date_labels = "%Y")

enter image description here

dc37
  • 15,840
  • 4
  • 15
  • 32