有没有办法在R中使用普通的Dygraphs JavaScript选项(具体来说,还有Shiny)?
http://dygraphs.com/options.html
我认为htmlwidgets包中的JS()
函数可以使用,但不确定。
例如,我想使用highlightSeriesOpts
(参见第一个链接)突出显示书本图中的单个系列,以便仅在图例中显示选定的系列(默认情况下并非同时显示所有系列)。以下链接中的下部2个图准确显示了要实现的目标:
http://dygraphs.com/gallery/#g/highlighted-series
已经提供了CSS解决方案(即.dygraph-legend {display: none;}
和.dygraph-legend .highlight {display: inline;}
),但是在R / Shiny中不起作用。
无论如何,这是我的概念脚本。它不起作用,但是所有建议都值得赞赏。
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)
最佳答案
highlightSeriesOpts
导致突出显示的系列笔划变粗,并且不影响图例。您仍然需要适当的CSS
以仅显示图例中最接近的系列。要按照您的建议设置highlightSeriesOpts
,在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))
要获得Shiny中更完整的答案,我们可以做这样的事情。
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)
关于javascript - R/Shiny中的Plain Dygraphs JavaScript选项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35943583/