I am trying to add ticks to my x-axis in this graph to show all the months of the year:
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"
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"))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With