John Smith
John Smith

Reputation: 1698

Multiples annotations (with a data.frame) in dygraphs with R

There is a package in R for dygraphs, and it is possible to add annotations: https://rstudio.github.io/dygraphs/gallery-annotations.html

dygraph(presidents, main = "Quarterly Presidential Approval Ratings") %>%
  dyAxis("y", valueRange = c(0, 100)) %>%
  dyAnnotation("1950-7-1", text = "A", tooltip = "Korea") %>%
  dyAnnotation("1965-1-1", text = "B", tooltip = "Vietnam")

I would like to how it is possible to create a data.frame in order to organise all annotations and add with a single dyAnnotation option. I tried:

dygraph(presidents, main = "Quarterly Presidential Approval Ratings") %>%
  dyAxis("y", valueRange = c(0, 100)) %>%
  dyAnnotation(c("1950-7-1","1965-1-1"), text = c("A","B"), tooltip = c("Korea","Vietnam"))

It doesn't work.

Upvotes: 4

Views: 1124

Answers (1)

Maju116
Maju116

Reputation: 1607

You can do something like this:

Step 1. Create a basic dygraph without annotations and save it as object (not really required but creates shorter strings in Step 2):

dygraph(presidents, main = "Quarterly Presidential Approval Ratings") %>%
  dyAxis("y", valueRange = c(0, 100)) -> graph

Step 2. Create two (if you want tooltips also create three) vectors with dates and texts for your annotations. Then create below string:

 dates<-c("1950-7-1","1965-1-1","1972-1-1")
 texts<-c("a","bb","cc")

 my_code<-paste("graph %>%",
 paste0("dyAnnotation('",dates,"',text='",texts,"')",collapse = " %>% "))

You will get something like this:

"graph %>% dyAnnotation('1950-7-1',text='a') %>% dyAnnotation('1965-1-1',text='bb') %>% dyAnnotation('1972-1-1',text='cc')"

Step 3. Use eval and parse functions:

  eval(parse(text = my_code))

Multiply annotations

If you want to create an object containing this graph chcnage the string in Step 2:

my_code<-paste("graph2<- graph %>%",
  paste0("dyAnnotation('",dates,"',text='",texts,"')",collapse = " %>% "))

Upvotes: 2

Related Questions