Reputation: 117
I am trying to replace the x-axis values created using step, which are values 1:50. I can replace these easily using scale_x_continuous but when I use breaks I get the error below. I cannot use date and time in the plot function I am using so looking for a work around to get date on my axis
Date = c( "2018-10-18 00:00:00 BST", "2018-10-18 00:10:00 BST", "2018-10-18 00:20:00 BST", "2018-10-18 00:30:00 BST", "2018-10-18 00:40:00 BST", "2018-10-18 00:50:00 BST",
"2018-10-18 01:00:00 BST", "2018-10-18 01:10:00 BST", "2018-10-18 01:20:00 BST", "2018-10-18 01:30:00 BST", "2018-10-18 01:40:00 BST", "2018-10-18 01:50:00 BST",
"2018-10-18 02:00:00 BST", "2018-10-18 02:10:00 BST", "2018-10-18 02:20:00 BST", "2018-10-18 02:30:00 BST", "2018-10-18 02:40:00 BST", "2018-10-18 02:50:00 BST",
"2018-10-18 03:00:00 BST", "2018-10-18 03:10:00 BST", "2018-10-18 03:20:00 BST", "2018-10-18 03:30:00 BST", "2018-10-18 03:40:00 BST", "2018-10-18 03:50:00 BST",
"2018-10-18 04:00:00 BST", "2018-10-18 04:10:00 BST", "2018-10-18 04:20:00 BST", "2018-10-18 04:30:00 BST", "2018-10-18 04:40:00 BST", "2018-10-18 04:50:00 BST",
"2018-10-18 05:00:00 BST", "2018-10-18 05:10:00 BST", "2018-10-18 05:20:00 BST", "2018-10-18 05:30:00 BST", "2018-10-18 05:40:00 BST", "2018-10-18 05:50:00 BST",
"2018-10-18 06:00:00 BST", "2018-10-18 06:10:00 BST", "2018-10-18 06:20:00 BST", "2018-10-18 06:30:00 BST", "2018-10-18 06:40:00 BST", "2018-10-18 06:50:00 BST",
"2018-10-18 07:00:00 BST", "2018-10-18 07:10:00 BST", "2018-10-18 07:20:00 BST", "2018-10-18 07:30:00 BST", "2018-10-18 07:40:00 BST", "2018-10-18 07:50:00 BST",
"2018-10-18 08:00:00 BST", "2018-10-18 08:10:00 BST")
Step <- c(1:50)
Value <- runif(50,0,10)
Final <- data.frame(Step, Value)
ggplot(Final, aes(x = Step, y = Value)) +
geom_line(size = 1) +
geom_point() +
scale_x_continuous(labels=Date,breaks = seq(1, 50)) #works
scale_x_continuous(labels=Date,breaks = seq(1, 50,by=10)) #doesntwork
Error: `breaks` and `labels` must have the same length
Upvotes: 3
Views: 2379
Reputation: 29
I would drop creating Step
and just use your dates directly as the X-value in your plot.
The reason R won't subset is because it considers your 50 dates as 50 strings.
Convert to a datettime class and manipulate it with scale_x_datetime()
:
Value <- runif(50,0,10)
Final <- data.frame(Value, Date)
Final$Date = as.POSIXct(Date)
ggplot(Final, aes(x = Date, y = Value, group = 1)) +
geom_line(size = 1) +
geom_point() +
scale_x_datetime(date_breaks = "2 hours", date_labels = "%H:%M")
Upvotes: 1
Reputation: 46908
You need to subset your lables (Dates in your case) too:
ggplot(Final, aes(x = Step, y = Value)) +
geom_line(size = 1) +
geom_point() +
scale_x_continuous(labels=Date[seq(1, 50,by=10)],
breaks = seq(1, 50,by=10))
Upvotes: 3