Is there a way to use plain Dygraphs JavaScript options in R (and Shiny more in specific)?
http://dygraphs.com/options.html
I think the JS()
function from the htmlwidgets package can be of use, but am not sure.
For example, I want to use highlightSeriesOpts
(cf. first link) to highlight individual series in a dygraphs plot in order to display ONLY the selected series in the legend (and not all series at the same time by default). The lower 2 plots in the following link show exactly what is to be achieved:
http://dygraphs.com/gallery/#g/highlighted-series
A CSS solution has already been given ( i.e. .dygraph-legend {display: none;}
and .dygraph-legend .highlight {display: inline;}
), but that somehow does not work in R/Shiny.
Anyhow, here is a conceptual script of mine. It does not work, but all advice is much appreciated.
ui <- fluidPage(
sidebarLayout(
sidebarPanel(),
mainPanel(dygraphOutput("plot"))
)
)
server <- function(input, output) {
set.seed(123)
data <- matrix(rnorm(12), ncol = 2)
data <- ts(data)
# Workaround for what might be a bug
# Reference: http://stackoverflow.com/questions/28305610/use-dygraph-for-r-to-plot-xts-time-series-by-year-only
data <- cbind(as.xts(data[,1]), as.xts(data[,2]))
colnames(data) <- c("Series 1", "Series 2")
#print(data) # Uncomment to view data frame
# The logic of the following is that plain Dygraphs JavaScript
# code can be used as plotting material
output$plot <- JS("
new Dygraph(plot,
data,
{ highlightSeriesOpts: {strokeWidth: 3} });
g.updateOptions({ highlightSeriesOpts: {strokeWidth: 3} });
")
}
shinyApp(ui = ui, server = server)
The highlightSeriesOpts
causes the highlighted series stroke to be bolder and does not affect the legend. You will still need the proper CSS
to only show the closest series in the legend. To set the highlightSeriesOpts
as you suggest, there is a clear example at http://rstudio.github.io/dygraphs/gallery-series-highlighting.html.
lungDeaths <- cbind(ldeaths, mdeaths, fdeaths)
dygraph(lungDeaths, main = "Deaths from Lung Disease (UK)") %>%
dyHighlight(highlightSeriesOpts = list(strokeWidth = 3))
For a fuller answer in Shiny, we could do something like this.
library(shiny)
library(dygraphs)
lungDeaths <- cbind(ldeaths, mdeaths, fdeaths)
ui <- dygraph(lungDeaths, main = "Deaths from Lung Disease (UK)") %>%
dyHighlight(highlightSeriesOpts = list(strokeWidth = 3)) %>%
dyCSS(textConnection("
.dygraph-legend > span { display: none; }
.dygraph-legend > span.highlight { display: inline; }
"))
server <- function(input,output,session){
}
shinyApp(ui,server)