Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding date ticks to ggplot in R

Tags:

r

ggplot2

I am trying to add ticks to my x-axis in this graph to show all the months of the year:

enter image description here

My code is as follows:

library(ggplot2)
library(scales)
p <- ggplot(df_test, aes(time, reading))
p + geom_point(alpha = 1/4) + geom_smooth()

I have tried to use scale_x_date but have come across the following error:

Error: Invalid input: date_trans works with objects of class Date only

Here's the data frame I'm using:

 hour   reading   date                time
 1      53        1/1/15 2015-01-01 01:00:00
 2      55        1/1/15 2015-01-01 02:00:00
 3      56        1/1/15 2015-01-01 03:00:00

The class of my time variable:

class(df_test$time) "POSIXct" "POSIXt"

like image 945
timothyylim Avatar asked Jan 08 '23 13:01

timothyylim


2 Answers

Use scale_x_date(breaks="month", labels=date_format("%b%)). Here's an example.

library(quantmod)
sp500 <- getSymbols("SP500", src="FRED", auto.assign=FALSE)
sp500 <- sp500["2015-01-01::"]
sp500 <- data.frame(time=as.POSIXct(index(sp500), origin="1970-01-01"),sp500)
class(sp500$time)
# [1] "POSIXct" "POSIXt" 

library(ggplot2)
library(scales)    # for date_format(...)
ggplot(sp500, aes(x=as.Date(time), y=SP500))+
  geom_line()+
  scale_x_date(breaks="month", labels=date_format("%b"))

enter image description here

like image 184
jlhoward Avatar answered Jan 14 '23 07:01

jlhoward


You are trying to use a scale specific for Date on a POSIXct object. The solution is to cast the POSIXct object to a date using as.date:

> Sys.time()
[1] "2015-09-16 09:52:42 CEST"
> as.Date(Sys.time())
[1] "2015-09-16"

To do this on your data.frame, I recommend using the dplyr package:

df_test = df_test %>% mutate(time = as.Date(time))
like image 22
Paul Hiemstra Avatar answered Jan 14 '23 07:01

Paul Hiemstra