highcharts R highchart xrange 24小时图表

ebdffaop  于 2023-10-20  发布在  Highcharts
关注(0)|答案(1)|浏览(175)

我已经参考了xrange图表的例子,来自这个链接https://jkunst.com/highcharter/articles/highcharts.html
我的xrange图表的x轴在一天内(24小时周期),不像原来的例子。
根据数据,该图不能正确反映时间。有什么办法解决吗?

library(data.table)
library(lubridate)
library(highcharter)

N <- 7

DT <- data.table(start = c("2023-09-04 05:45:01 CST","2023-09-04 06:28:17 CST",
     "2023-09-04 06:51:39 CST","2023-09-04 07:25:30 CST","2023-09-04 08:20:13 CST",
     "2023-09-04 09:20:41 CST","2023-09-04 09:34:33 CST"),
             end = c("2023-09-04 07:10:38 CST","2023-09-04 07:38:01 CST",
      "2023-09-04 08:35:34 CST","2023-09-04 08:48:26 CST","2023-09-04 09:29:07 CST",
      "2023-09-04 10:30:34 CST","2023-09-04 10:53:42 CST"),
             methods =  c("Prototyping", "Development","Testing", "Validation", 
                         "Modelling","Prototyping","Development"),
             cat = rep(1:5, length.out = N) - 1, progress = round(stats::runif(N), 1))%>%
      mutate(StDay_Time = 
            as.numeric(as.POSIXct(start,
                    format="%Y-%m-%d %H:%M:%S",tz="Asia/Taipei"))*1000)%>%
      mutate(EnDay_Time = 
            as.numeric(as.POSIXct(end,format="%Y-%m-%d  %H:%M:%S",tz="Asia/Taipei"))*1000)

     hchart(DT,"xrange",
        hcaes(x = StDay_Time, x2 = EnDay_Time, y = cat,partialFill = progress),
        dataLabels = list(enabled = TRUE))%>% 
        hc_xAxis(title = FALSE,type = "datetime")%>% 
        hc_yAxis(title = FALSE,categories = DT$methods)

我相信我的数据格式可能有一些问题,以适应 highcharts 的x轴时间轴。也许它没有按照时区或UNIX时间戳正确格式化。
感谢任何可能的帮助,谢谢。

r3i60tvu

r3i60tvu1#

如果您指的是时间显示不正确(例如,时区偏移),这可能是由于highcharter包将时间转换为UTC。
让我们尝试以下方法:
1.将日期转换为POSIXct格式时,使用tz =“UTC”确保日期被视为UTC时间。
1.将X轴的格式设置为使用日期格式“%Y-%m-%d %H:%M:%S”,以便显示完整的日期和时间(不含毫秒)。
下面是修改后的代码:

library(data.table)
library(lubridate)
library(highcharter)

N <- 7

DT <- data.table(
  start = c("2023-09-04 05:45:01 CST","2023-09-04 06:28:17 CST",
            "2023-09-04 06:51:39 CST","2023-09-04 07:25:30 CST",
            "2023-09-04 08:20:13 CST","2023-09-04 09:20:41 CST",
            "2023-09-04 09:34:33 CST"),
  end = c("2023-09-04 07:10:38 CST","2023-09-04 07:38:01 CST",
          "2023-09-04 08:35:34 CST","2023-09-04 08:48:26 CST",
          "2023-09-04 09:29:07 CST","2023-09-04 10:30:34 CST",
          "2023-09-04 10:53:42 CST"),
  methods = c("Prototyping", "Development","Testing", "Validation", 
              "Modelling","Prototyping","Development"),
  cat = rep(1:5, length.out = N) - 1,
  progress = round(stats::runif(N), 1)
)

DT[, StDay_Time := as.numeric(as.POSIXct(start, format="%Y-%m-%d %H:%M:%S", tz="UTC"))*1000]
DT[, EnDay_Time := as.numeric(as.POSIXct(end, format="%Y-%m-%d %H:%M:%S", tz="UTC"))*1000]

hchart(DT,"xrange",
       hcaes(x = StDay_Time, x2 = EnDay_Time, y = cat,partialFill = progress),
       dataLabels = list(enabled = TRUE))%>% 
  hc_xAxis(title = FALSE,type = "datetime")%>% 
  hc_yAxis(title = FALSE,categories = DT$methods)

相关问题