r - 在 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
解决方案
感谢您提供所有代码,我终于能够运行您的图表并找到解决方案。
您需要创建所有 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)
推荐阅读
- json - 模型的 JSON 组织
- tensorflow - ValueError:('无法解释初始化标识符:',0.2)
- android - Android9.0 InputMethod超出屏幕范围
- c# - System.IO.FileLoadException:无法加载文件或程序集'Pkcs11Interop,版本 = 3.3.0.0
- python - 不能将 TimeDistributed 与 LSTM 一起使用
- firebase - 值事件如何处理 Firebase 监听器的更新?
- machine-learning - 为什么输出 LSTM 层的维度可以是 2 维或 3 维?
- mysql - MySQL:基于另一列的值的列的总和
- multithreading - Rails Thread.current 变量是否与单个用户请求隔离?
- javascript - 什么构成用户手势