【问题标题】:How to add values ​between hours如何在小时之间添加值
【发布时间】:2021-05-05 21:11:44
【问题描述】:

我有将具有相应值的小时分解为一刻钟的代码。 不幸的是,当分解为一刻钟时,整个小时的值是相同的。 添加刻钟后,我还想在原始小时之间添加值,以使图形平滑且不锐利。怎么做,平均,插值?

df <- data.frame(
  h = 0:23,
  x = c(22, 11, 5, 8 , 22, 88, 77, 7, 11, 5, 8 , 22, 88, 77, 11, 5, 8 , 22, 88, 77, 11, 5, 8 , 22))

library(dplyr)
library(stringr)
df %>%
  data.frame(h = rep(df$h, each = 4),                             # quadruplicate rows
             x = rep(df$x, each = 4)) %>%                         # quadruplicate rows 
  mutate(h.1 = str_pad(h.1, width = 2, side = "left", pad = "0"), # add leading '0'
         qu = paste0(h.1, c(":00", ":15", ":30", ":45"))) %>%     # create quarters
  select( - c(h,x)) %>%                                           # deselect obsolete cols
  rename(c("h" = "h.1", "x" = "x.1"))  

 df %>%
  ggplot() +
  geom_point(aes(qu, x), color = "red", size = 2) +
  labs(x= "", y = "",
       title = "Example")

【问题讨论】:

    标签: r ggplot2 time


    【解决方案1】:

    在这里我做了一个“十进制小时”变量来简化计算。我们也可以使用hms::hms()来定义一个ggplot2可以理解的时间戳。我在这里使用base:approx 在每小时点之间进行插值。

    df2 <- df %>%
      tidyr::uncount(4) %>%  # make 4 copies of each row
      mutate(h_dec = h + (0:3)/4,
             h_time = hms::hms(hours = h_dec),
             x = x * c(1, NA, NA, NA),  # this is to make non-hourly into NA,
                                        # so that approx only uses hourly
             x_interp = approx(x = h, y = x, xout=h_dec)$y)
             
    df2 %>%
      ggplot() +
      geom_point(aes(h_time, x_interp), color = "red", size = 2) +
      labs(x= "", y = "",
           title = "Example")
    

    【讨论】:

    • 这就是我的意思,谢谢。 :) 时间格式也发生了变化,例如带有时间的日期:2021-04-13 01:00:00 是否可以在 2021-04-13 01:00、2021-04-13 01 的代码中进行修改: 15, 2021-04-13 01:30, 2021-04-13 01:45, ... ?
    • 试试h_time = lubridate::ymd_hm(paste("2021-04-13", h, c(0, 15, 30, 45)))
    • 使用这段代码,我一直都有相同的时间,不幸的是一刻钟不变。 df2 % tidyr::uncount(4) %>% # 每行复制 4 份 mutate(h_dec = datetime+ (0:3)/4) 一刻钟不加。
    • 当我将建议的行 h_time = lubridate::ymd_hm(paste("2021-04-13", h, c(0, 15, 30, 45))), 放在 h_time = hms::hms(hours = h_dec), 的位置或之后时,我会得到基于 4 月 13 日的 x 轴的预期结果。
    • 我想你会在x_interp = approx(x = h, y = x, xout=h_dec)$y) 之后添加:%&gt;% mutate(rrr_interp = approx(x = rrr, y = x, xout=h_dec)$y) 其中rrr 是你现在拥有的相邻列。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多