Reputation: 15
I have data that are sampled hourly, and I plot the data accordingly;
x<-c("2016-05-09 09:00:00", "2016-05-09 10:00:00", "2016-05-09 11:00:00", "2016-05-10 12:00:00")
y<- c(2,NA,3,5)
df<-data.frame(x,y)
plot(df$x,df$y)
On the x-axis, I only want to display the timestamp as year-month-date. Additionally, I only want to display one single label per date (even though I have several measurements on the same date). Is there a way to do this? I prefer basic functions
Kind regards,
Upvotes: 0
Views: 398
Reputation: 15
I came up with a solution. Perhaps its not the best one but here it goes:
I supressed the plotting of the x-axis par(xaxt='l), then I created a new xaxis using axis(). I sequenced the ticks from 1 to the total number of hours that have measurements (note that this is continuous data) by 24 (number of hours per day), then I added my own labels using labels=c("2016-05-09", ..) in axis().
Note that this solution worked since I only had ~10 days of data to show. I suppose the approach would be unsuitable for long timeseries.
#Hourly data
x<-c("2016-05-09 00:00:00","2016-05-09 01:00:00", "2016-05-09 02:00:00", "2016-05-09 03:00:00", "2016-05-09 04:00:00", "2016-05-09 05:00:00","2016-05-09 06:00:00","2016-05-09 07:00:00","2016-05-09 08:00:00","2016-05-09 09:00:00","2016-05-09 10:00:00","2016-05-09 11:00:00","2016-05-09 12:00:00","2016-05-09 13:00:00","2016-05-09 14:00:00","2016-05-09 15:00:00","2016-05-09 16:00:00","2016-05-09 17:00:00","2016-05-09 18:00:00","2016-05-09 19:00:00","2016-05-09 20:00:00","2016-05-09 21:00:00","2016-05-09 22:00:00","2016-05-09 23:00:00","2016-05-10 00:00:00")
y<-seq(1,length(x),by=1)
df<-data.frame(x,y)
#Suppress x-axis
plot(df$x,df$y,xaxt='n')
#Create new x-axis with ticks in 24 hour interval
axis(side=1,at=seq(1,length(x),by=24),labels=c("2016-05-09","2016-05-10"))
Upvotes: 1
Reputation: 7832
Doing this with ggplot is fairly easy, because you can use scale_x_date()
(you need to convert x
to date with as.Date()
).
x <-
as.Date(
c(
"2016-05-09 09:00:00",
"2016-05-09 10:00:00",
"2016-05-09 11:00:00",
"2016-05-10 12:00:00"
)
)
y <- c(2, NA, 3, 5)
df <- data.frame(x, y)
library(ggplot2)
ggplot(df, aes(x = x, y = y)) + geom_line() + scale_x_date()
Upvotes: 0