Rod*_*eda 4 jquery r shiny plotly
我正在使用jQuery(jQuery Core 2.1.4)来开发我的Shiny应用程序的一部分。此外,我正在使用新plotly程序包来绘制图。jQuery也可以完美地工作plotly。但是,当同时使用这两种方法时,这些图将plotly消失。调用jQuery似乎是原因。
是否有一种变通办法,允许在同一Shiny App中使用jQuery和
plotly(特别是ggplotly)?
这是一个例子。我知道这个示例不需要jQuery,而只是为了说明plotly在包括jQuery时情节如何消失(取消注释#tags$head(tags$script(src='http://code.jquery.com/jquery-2.1.4.js')),以包括该行):
#Call the required libraries
library(shiny)
library(plotly)
library(ggplot2)
#Server to output plot
server <- shinyServer(function(input, output) {
output$plotlyout <- renderPlotly({
#Create random points
x <- rnorm(100)
y <- rnorm(100)
#Set to data frame
dats <- as.data.frame(cbind(x,y))
#Plot them in plotly
ggplotly(ggplot(dats) + geom_point(aes(x = x, y = y)))
})
})
#Shiny plot
ui <- shinyUI(
#One page with main Panel
fluidPage(
#Uncomment this to see how Jquery ruins everything
#tags$head(tags$script(src='http://code.jquery.com/jquery-2.1.4.js')),
#Panel for plot
mainPanel(
#Output plot
plotlyOutput("plotlyout")
)
)
)
shinyApp(ui = ui, server = server, options = list(launch.browser = TRUE))
Run Code Online (Sandbox Code Playgroud)
谢谢!
解决方案:您需要使用JQuery的noconflict()。tags$head(tags$script("$.noConflict(true);")), 在加载jquery的行之后添加。
说明:默认情况下,Shiny已加载JQuery。您可以通过查看任何Shiny应用程序页面的源代码来查看此内容,并看到它加载了jquery。当我运行您的应用程序并查看JavaScript控制台中的错误时,我遇到了奇怪的错误,这些错误表明JQuery的某些功能无法正常工作。因此,我认为“嗯,jquery肯定已加载。它实际上已加载两次。但是,当我加载两次时,它不起作用。让我们使用Google!”。因此,如果您通过Google搜索如何在一个页面上两次加载jquery,则会看到很多回答说要使用noconflict()。在您的jquery行之后添加它似乎可以解决问题。