我正在尝试使用hchart在x轴上具有多个事件行的时序图。类似于this question中所需的图所示。但是我无法引入多行,而是只得到与第一个值相对应的行。有什么方法可以在hc_xAxis内循环绘制绘图线值?
下面是我的代码:
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)
}
And here is the graph that I get for the above code
显示的绘图线是与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)