【问题标题】:R plot function removes hours in x axisR plot 函数删除 x 轴上的小时数
【发布时间】:2020-01-11 08:37:34
【问题描述】:

我想在 R 中的一个简单图中显示以下数据框:

> df
  value            dateTime
1 -0.8 2018-04-02 06:00:00
2 -0.7 2018-04-02 06:01:00
3 -0.6 2018-04-02 06:02:00
4 -0.7 2018-04-02 06:03:00
5 -0.5 2018-04-02 06:04:00
6 -0.9 2018-04-02 06:05:00

> plot(df$dateTime, df$value, type = "o", xlab = "Time", ylab = "Value", cex.axis = 1.5, cex.lab = 1.5, cex.main = 1.5, ylim=c(-1,1))

结果是:

如您所见,该图仅在 x 轴上显示分钟和秒。但是,我想在 x 轴上有小时和分钟。

【问题讨论】:

    标签: r datetime plot axis


    【解决方案1】:

    对不起,我之前的回答令人困惑。我认为ggplot2 会做:

    library(tidyverse)
    library(lubridate)
    library(scales)
    df<-tibble(
      value = c(-0.8, -0.7, -0.6, -0.7, -0.5, -0.9), 
      dateTime = ymd_hms(
         "2018-04-02 06:00:00", "2018-04-02 06:01:00",
         "2018-04-02 06:02:00", "2018-04-02 06:03:00",
         "2018-04-02 06:04:00", "2018-04-02 06:05:00") )
    
    ggplot(data = df, aes(x = dateTime,  y = value)) + 
      geom_line() + scale_x_datetime(breaks = date_breaks("1 min"), 
                   labels = date_format("%H:%M"))
    

    【讨论】:

    • 你添加library(scales)了吗?
    【解决方案2】:

    最好单独添加 x 轴。通过设置xaxt="n"plot() 中禁用它。然后我们可以使用axis.POSIXct() 再次添加它,它的参数format 让我们可以指定日期和时间的表示方式。请查看?strptime 了解如何指定此格式。

    df <- structure(list(value=c(-0.8, -0.7, -0.6, -0.7, -0.5, -0.9),
      dateTime=structure(c(1522641600, 1522641660, 1522641720,
      1522641780, 1522641840, 1522641900), class=c("POSIXct",
      "POSIXt"), tzone="")), class="data.frame", row.names=c(NA,
      -6L))
    
    plot(df[,2:1], ylim=c(-1, 1), xaxt="n", type="o")
    axis.POSIXct(1, df$dateTime, format="%H:%M")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 2020-11-11
      • 1970-01-01
      • 2019-10-21
      相关资源
      最近更新 更多