dynamically add events to dygraph r

1.1k views Asked by At

I have a dataframe with selected dates from a time series that are outliers. I want to dynamically add them to my dygraph as event lines. My data looks like this

> head(data)
  Group Date
1 g1 2013-08-26
2 g1 2013-08-27
3 g2 2013-08-29
4 g2 2013-12-31
5 g3 2014-01-08

df_sub <- data[data$Group=='g1',]

I'm trying to create a function that takes in a group name and created a dygraph with outliers as event lines.

In my eg. for g1, there are two dates with outliers.

Since the basic function looks like this:

p <- dygraph(df_sub) %>% dyEvent(date = '2013-08-26', label='xyz', labelLoc='bottom')

I want to dynamically pass two dates and get two event lines. As dyEvent only takes one date, is there a way to do this for multiple dates ?

Thanks

1

There are 1 answers

0
user2996185 On BEST ANSWER

I figured out that you can build dygraph plots like this:

p <- dygraph(df_sub)
p <- p %>% dyEvent(x = '2013-08-26', label='xyz', labelLoc='bottom')

Then calling p calls the plot. So you can create more event lines using for cycle:

p <- dygraph(df_sub)
for (i in 1:dim(df_sub)[1]){
p <- p %>% dyEvent(date = df_sub$Date[i], label='xyz', labelLoc='bottom')
}