在 R 中使用日期自定义 x 轴标签

Customize x-axis labels with dates in R

我有每小时采样的数据,我相应地绘制了数据;

    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)

在x轴上,我只想将时间戳显示为年-月-日。此外,我只想在每个日期显示一个标签(即使我在同一日期有多个测量值)。有没有办法做到这一点?我更喜欢基本功能

亲切的问候,

我想出了一个解决办法。也许它不是最好的,但它是这样的:

我抑制了 x-axis par(xaxt='l) 的绘图,然后我使用 axis() 创建了一个新的 xaxis。我将刻度从 1 到具有测量值的总小时数(注意这是连续数据)按 24(每天的小时数)排序,然后我使用 labels=c("2016-05-09 ", ..) 在 axis() 中。

请注意,此解决方案有效,因为我只有大约 10 天的数据要显示。我想这种方法不适合长时间序列。

    #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"))

使用 ggplot 执行此操作相当简单,因为您可以使用 scale_x_date()(您需要将 x 转换为 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()