Failing to increase x-axis ticks with usual code

Viewed 23

I have a daily dataframe that I would like to plot:


xx=data.frame(Date = seq(as.Date("2001-01-01"), as.Date("2020-12-31"), by = "day"),
              Data = randn(length(seq(as.Date("2001-01-01"), as.Date("2020-12-31"), by = "day")),1),
              stringsAsFactors = F)

I then plot it like this:

ggplot(xx) +
  geom_line(aes(x = Date, y = Data), col = "blue") +
  labs(y = "", x = "") + theme_classic()

Yet, I want to have every year on the x-axis and when I try to do it like this:


ggplot(xx) +
  geom_line(aes(x = Date, y = Data), col = "blue") +
  labs(y = "", x = "") + theme_classic() +
  scale_x_continuous(breaks = seq(min(xx$Date), max(xx$Date), by = "year"))

I get: Error in as.Date.numeric(value) : 'origin' must be supplied. I don't manage to sort this.

Can anyone help me?

Thanks!

1 Answers

Try with this:

#Data
xx=data.frame(Date = seq(as.Date("2001-01-01"), as.Date("2020-12-31"), by = "day"),
              Data = randn(length(seq(as.Date("2001-01-01"), as.Date("2020-12-31"), by = "day")),1),
              stringsAsFactors = F)
#Code
ggplot(xx) +
  geom_line(aes(x = Date, y = Data), col = "blue") +
  labs(y = "", x = "") + theme_classic() +
  scale_x_date(breaks = seq(min(xx$Date), max(xx$Date), by = "year"),
               date_labels = '%Y')

Output:

enter image description here

Related