Reputation: 5542
I have a dataframe:
bvar time
0.000000000 2003-03-14 19:00:00
0.200000000 2003-03-14 20:00:00
0.044000000 2003-03-14 21:00:00
Here, time is POSIXct:
str(tsdat$time)
POSIXct[1:193], format: "2003-03-14 19:00:00"
When I plot it, I want to control the x-axis by showing every hour:
ggplot(ts) +
geom_line(aes(x=time, y=bvar))+
theme(axis.text.x = element_text(angle = 0, hjust = 1))+
scale_x_date(labels=date_format("%Y %H:%M")) +
ylab('BVAR [mm]')
Error: Invalid input: date_trans works with objects of class Date only
How can I make this hourly? In another question, they suggested using as.Date
. But this doesn't work for me as my data is for 2 days only.
Upvotes: 2
Views: 1055
Reputation: 30494
I think you can use scale_x_datetime
for POSIXct instead of scale_x_date
. To get hourly breaks on the xaxis, also add breaks = "1 hour"
.
library(ggplot2)
library(scales)
ggplot(ts) +
geom_line(aes(x=time, y=bvar))+
theme(axis.text.x = element_text(angle = 0, hjust = 1))+
scale_x_datetime(labels=date_format("%Y %H:%M"), breaks = "1 hour") +
ylab('BVAR [mm]')
Output
Data
ts <- structure(list(bvar = c(0, 0.2, 0.044), time = structure(c(1047690000,
1047693600, 1047697200), class = c("POSIXct", "POSIXt"), tzone = "")), row.names = c(NA,
-3L), class = "data.frame")
Upvotes: 2