【问题标题】:Specify beginning and end limits for 24 hour time axis in ggplot在 ggplot 中指定 24 小时时间轴的开始和结束限制
【发布时间】:2021-12-13 22:11:17
【问题描述】:

我正在绘制从 16:00 到 06:00 夜间收集的数据的风​​速与时间的关系图。我希望图表连续显示这些时间,从 16:00 到 06:00,午夜更靠近 x 轴的中心。我当前的图表以中午为中心。

这是我目前的图表:

代表代码:

wind_speed <- structure(list(time_start = structure(c(0, 3600, 7200, 10800, 
                                        14400, 18000, 21600, 57600, 61200, 64800, 68400, 72000, 75600, 
                                        79200, 82800), class = c("hms", "difftime"), units = "secs"), 
               wind_avg = c(1.60133333333333, 1.54866666666667, 0.900666666666667, 
                            1.28766666666667, 1.78533333333333, 0.678666666666667, 1.00733333333333, 
                            0.531, 0.821666666666667, 0.119666666666667, 0.401333333333333, 
                            0.501333333333333, 0.769333333333333, 1.797, 1.52266666666667
               ), time_of_day = c("00:00", "01:00", "02:00", "03:00", "04:00", 
                                  "05:00", "06:00", "16:00", "17:00", "18:00", "19:00", "20:00", 
                                  "21:00", "22:00", "23:00")), row.names = c(NA, -15L), class = c("tbl_df", 
                                                                                                  "tbl", "data.frame"))

library(ggplot2)
ggplot(data = wind_speed, aes(x = time_start, y = wind_avg))+
  geom_point() 

谢谢!

【问题讨论】:

    标签: r datetime ggplot2 axis-labels


    【解决方案1】:

    另一种选择是将您的 x 变量转换为时间类。更好:日期时间。为什么约会?添加“日期”信息将帮助 R 知道 0 到 6 小时应该是在午夜之后。如果您忽略此信息,您可能会让自己的生活变得非常困难。

    如果您没有该日期信息,我会添加一个随机日期,例如今天。

    然后您可以使用scale_x_datetime,它会自动为您提供正确的限制。 (其实你甚至不需要添加它,因为ggplot会自动识别日期时间类。)

    library(tidyverse)
    library(lubridate)
    
    wind_speed %>% 
      # add "day", then convert to actual date time class
      # using Sys.Date is random, just to get a date. 
      mutate(day = as_date(ifelse(time_of_day <="06:00", Sys.Date()+1, Sys.Date())),
        time_of_day = ymd_hm(paste(day, time_of_day))) %>%
    ggplot(aes(x = time_of_day, y = wind_avg))+
      geom_point() 
    

    reprex package (v2.0.1) 于 2021-12-23 创建

    【讨论】:

      【解决方案2】:

      知道了:

      library(tidyverse)
      
      #create character vector of measurement start times
      wind_speed <- wind_speed %>% mutate(time_of_day = strftime(time_start, format = "%H:%M"))
      
      ggplot(data = wind_speed, aes(x = time_of_day, y = wind_avg))+
        geom_point()+
        scale_x_discrete(limits = c("16:00","17:00","18:00","19:00","20:00","21:00","22:00","23:00","00:00","01:00","02:00","03:00","04:00","05:00","06:00"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多