将日期刻度添加到 R 中的 ggplot

tim*_*lim 5 r ggplot2

我正在尝试在此图中的 x 轴上添加刻度以显示一年中的所有月份:

在此处输入图片说明

我的代码如下:

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

我尝试使用scale_x_date但遇到以下错误:

Error: Invalid input: date_trans works with objects of class Date only
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的数据框:

 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
Run Code Online (Sandbox Code Playgroud)

我的时间变量的类:

类(df_test$time)“POSIXct”“POSIXt”

jlh*_*ard 5

使用scale_x_date(breaks="month", labels=date_format("%b%)). 这是一个例子。

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"))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


tim*_*lim 2

结合@PaulHiemstra 和@jihoward 的答案,我设法找到了答案。

首先使用 dplyr 库重新处理数据:

library(dplyr)
df_test1 = df_test %>% mutate(time = as.Date(time))
Run Code Online (Sandbox Code Playgroud)

然后使用scale_x_dates:

library(ggplot2)
library(scales)
p <- ggplot(df_test1, aes(time, reading))
p + geom_point(alpha = 1/4)+
  scale_x_date(breaks="month", labels=date_format("%b"))
Run Code Online (Sandbox Code Playgroud)

给出结果:

在此输入图像描述