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

别等时光非礼了梦想. 提交于 2019-12-11 00:58:22

问题


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.


回答1:


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))

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 = " %>% "))


来源:https://stackoverflow.com/questions/38182294/multiples-annotations-with-a-data-frame-in-dygraphs-with-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!