I am trying to get a time-series graph using hchart with multiple event lines on the x-axis. Something like what's shown as the needed graph in this question. But am not able to bring in the multiple lines, instead, I get only the line corresponding to the first value. Is there any way to loop the plotline values inside the hc_xAxis?
Below is my code:
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
The plotline shown is the one corresponding to the first value of 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
Thanks for providing all of your code, I was finally able to run your chart and find a solution.
You need to create a list of all plotLines and add this list to one chart - not creating many charts with one plotLine.
Here is a code that creates a plotLines list:
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')))
}
And this is the whole code:
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)