首页 > 解决方案 > 在 hchart 内循环:需要从存储在向量中的日期获取 hchart 内的多个绘图线

问题描述

我正在尝试使用 hchart 在 x 轴上有多个事件线来获取时间序列图。类似于此问题中所需图表所示的内容。但是我不能引入多行,相反,我只得到与第一个值对应的行。有没有办法在 hc_xAxis 内循环 plotline 值?

下面是我的代码:

for (i in 1:nrow(datevector)){
  hc <-  hchart(tseries, name = "Crimes") %>% 
  hc_add_series(arrests_tseries, name = "Arrests") %>%
  hc_add_theme(hc_theme_ffx()) %>%
  hc_credits(enabled = TRUE, text = "Sources: City of Chicago Administration and the Chicago Police Department", style = list(fontSize = "12px")) %>%
  hc_title(text = "Chicago Crimes and Arrests for 2016") %>%
  hc_legend(enabled = TRUE) %>%
  hc_xAxis(type = 'datetime', 
           plotLines = list(
                       list(
                       color = "rgba(100, 0, 0, 0.1)",
                       width = 5,
                       value = datetime_to_timestamp(as.Date(datevector[i,], tz = UTC')))))

print(hc)
}

这是我为上述代码得到的图表

显示的情节线是对应于 的第一个值的情节线datevector

> datevector
        Date
1 2016-07-16
2 2016-07-30
3 2016-06-11
4 2016-07-09
5 2016-09-17
6 2016-07-09
7 2016-06-18
8 2016-07-03
9 2016-07-16

标签: rhighchartsdata-visualizationr-highcharter

解决方案


感谢您提供所有代码,我终于能够运行您的图表并找到解决方案。

您需要创建所有 plotLines 的列表并将此列表添加到一个图表 - 而不是使用一个 plotLine 创建多个图表。

这是创建 plotLines 列表的代码:

plotLines <- list();
for (i in 1:nrow(datevector)){
  plotLines[[i]] <- list(
    color = "rgba(100, 0, 0, 0.1)",
    width = 5,
    value = datetime_to_timestamp(as.Date(datevector[i,], tz = 'UTC')))
}

这是整个代码:

library(lubridate)
library(ggplot2)
library(dplyr)
library(xts)
library(highcharter)

c16m16 <- read.csv("c16m16.csv")
m16 <- read.csv("m16.csv")

by_Date <- na.omit(c16m16) %>% group_by(Date) %>% summarise(Total = n())
tseries <- xts(by_Date$Total, order.by=as.POSIXct(by_Date$Date))
plot(tseries)                                 

Arrests_by_Date <- na.omit(c16m16[c16m16$Arrest == 'True',]) %>% group_by(Date) %>% summarise(Total = n())
arrests_tseries <- xts(Arrests_by_Date$Total, order.by=as.POSIXct(by_Date$Date))
plot(arrests_tseries)    

datevector <- as.vector(m16['Date'])

plotLines <- list();
for (i in 1:nrow(datevector)){
  plotLines[[i]] <- list(
    color = "rgba(100, 0, 0, 0.1)",
    width = 5,
    value = datetime_to_timestamp(as.Date(datevector[i,], tz = 'UTC')))
}

hc <-  hchart(tseries, name = "Crimes") %>% 
  hc_add_series(arrests_tseries, name = "Arrests") %>%
  hc_add_theme(hc_theme_ffx()) %>%
  hc_credits(enabled = TRUE, text = "Sources: City of Chicago Administration and the Chicago Police Department", style = list(fontSize = "12px")) %>%
  hc_title(text = "Chicago Crimes and Arrests for 2016") %>%
  hc_legend(enabled = TRUE) %>%
  hc_xAxis(type = 'datetime', plotLines = plotLines)

print(hc)

推荐阅读