在R中向ggplot添加日期刻度

时间:2015-09-16 07:05:15

标签: r ggplot2

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

enter image description here

我的代码如下:

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

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

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

这是我使用的数据框:

 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

我的时间变量类:

  

类(df_test $时间)   &#34; POSIXct&#34; &#34; POSIXt&#34;

4 个答案:

答案 0 :(得分:4)

您正尝试在Date对象上使用特定于POSIXct的比例。解决方案是使用POSIXctdate对象转换为as.date

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

要在data.frame上执行此操作,建议您使用dplyr包:

df_test = df_test %>% mutate(time = as.Date(time))

答案 1 :(得分:3)

使用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"))

enter image description here

答案 2 :(得分:2)

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

首先使用dplyr库重新编写数据:

library(dplyr)
df_test1 = df_test %>% mutate(time = as.Date(time))

然后使用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"))

给出结果:

enter image description here

答案 3 :(得分:0)

由于最近的答案 (2015) date_format() 已被弃用(我相信)。将其替换为 label_date()scales::label_date()。它可能未加载到您的命名空间中,但应与 ggplot 一起提供,因此可能需要 scales::

这是@timothylim 接受的答案的复制和粘贴,并进行了更改。

library(dplyr)
df_test1 = df_test %>% mutate(time = as.Date(time))

library(ggplot2)
library(scales)
p <- ggplot(df_test1, aes(time, reading))
p + geom_point(alpha = 1/4)+
  scale_x_date(breaks="month", labels = scales::label_date("%b"))
相关问题