首页 > 解决方案 > 如何为 highcharter columnrange 图使用日期范围?

问题描述

我正在尝试使用 Highcharter 创建一个列范围图,其中列表示日期范围。虽然这适用于整数,但不适用于日期。其他情节类型似乎可以很好地处理日期。

以天气 df 为例:

weather2 <- weather %>%
  filter(date <  mdy("03-31-2014"))%>% 
  mutate(low = date, high=date+30, id = row_number()) %>% 
  select(id, low, high)


hchart(weather2,
       type = "columnrange",
       hcaes(x = id, high=high, low=low)) 

该图只是呈现为空白,只有 x 轴标签。

但是,如果我只是将日期转换为整数,它会按预期显示一个范围。

weather3 <- weather %>%
  filter(date <  mdy("03-31-2014"))%>% 
  mutate(low = as.integer(date), high=as.integer(date+30), id = row_number()) %>% 
  select(id, low, high)

hchart(weather2,
       type = "columnrange",
       hcaes(x = id, high=high, low=low)) 

我也尝试过添加%>% hc_yAxis(type = "datetime"),但这也无济于事。

谢谢!

标签: rhighchartsr-highcharter

解决方案


似乎 columnrange 绘图类型要求日期为时间戳格式。它们可以使用datetime_to_timestamphighcharter 中的函数进行转换,然后使用hc_yAxis(type = "datetime").

weather2 <- weather %>%
  filter(date <  mdy("03-31-2014"))%>% 
  mutate(low = datetime_to_timestamp(date), 
         high = datetime_to_timestamp(date+30), 
         id = row_number()) %>% 
  select(id, low, high)


hchart(weather2,
       type = "columnrange",
       hcaes(x = id, high=high, low=low)) %>% 
hc_yAxis(type = "datetime")


推荐阅读