Search code examples
javascriptrdygraphs

How can I scale points in Dygraphs?


I am using the great dygraphs package for R (https://rstudio.github.io/dygraphs/)

My code as of right now is:

james<-mtcars[c("mpg","drat")]
james$date<-seq(from=as.Date("2013-05-16"),to=as.Date("2013-06-16"),by="days")
x <- xts::xts(james$mpg, order.by = james$date)
p <- dygraphs::dygraph(x, main = "mpg over time", xlab = "Date", ylab = "mpg") %>%
     dygraphs::dyRangeSelector() %>% 
     dyOptions(drawPoints = TRUE, pointSize = 2)
p

I want to scale the size of points in p by james$drat, rather than having it fixed at 2.

How can I do this?


Solution

  • I think the dygraphs javascript library has no option for varying point size within each series. A quite simple workaround is to create one series for every point size.
    Let us say we want 5 different point sizes, varying with james$drat. First, we create a binned variable with values 1-5 depending on the value of drat:

    drat_binned <- cut(james$drat, breaks=5, labels=1:5)
    

    Then we create 5 copies of the plot's y variable (james$mpg):

    james_new_variables <- matrix(rep(james$mpg, 5), nrow=nrow(james))
    

    For column number 1 we keep only the mpg values where drat_binnedequals 1, and correspondingly for columns number 2-5. The variables are then added to the original data set:

    for (i in 1:5)
      james_new_variables[drat_binned != i, i] <- NA
    james <- data.frame(james, james_new_variables)
    

    Then we make a new dygraph of the original variable plus the new variables (by default named X1-X5):

    x <- xts::xts(james[,c("mpg","X1","X2","X3","X4","X5")], order.by = james$date)
    p <- dygraphs::dygraph(x, main = "mpg over time", xlab = "Date", ylab = "mpg") %>%
      dygraphs::dyRangeSelector() %>% 
      dySeries("mpg") %>%
      dySeries("X1", color="blue", drawPoints = TRUE, pointSize = 2) %>%
      dySeries("X2", color="blue", drawPoints = TRUE, pointSize = 3) %>%
      dySeries("X3", color="blue", drawPoints = TRUE, pointSize = 4) %>%
      dySeries("X4", color="blue", drawPoints = TRUE, pointSize = 5) %>%
      dySeries("X5", color="blue", drawPoints = TRUE, pointSize = 6) %>%
    p
    

    Not very elegant, but sort of works. The only thing that reveals the trick used is the legend, which becomes messed up with the X1-X5 labels.