我正在使用jQuery (jQuery Core 2.1.4)开发我的 Shiny 应用程序的一部分。此外,我正在使用新的 plotly
包来渲染绘图。 jQuery 本身可以完美地工作,而且 plotly
也可以完美地工作;但是,当同时使用两者时,plotly
中的绘图就会消失。调用 jQuery 似乎是原因。
Is there a work-around that allows to use jQuery and
plotly
(specificallyggplotly
) in the same Shiny App?
这是一个例子。我知道这个例子不需要 jQuery,但只是为了说明当包含 jQuery 时 plotly
绘图如何消失(取消注释行 #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))
谢谢!
最佳答案
解决方案:需要使用JQuery的noconflict() 。添加 tags$head(tags$script("$.noConflict(true);")),
在加载 jquery 的行之后。
说明:Shiny 默认情况下已加载 JQuery。您可以通过查看任何 Shiny 应用程序页面的源代码来看到这一点,并且您将看到它加载了 jquery。当我运行您的应用程序并查看 JavaScript 控制台是否有错误时,我收到了奇怪的错误,表明 JQuery 的某些功能无法正常工作。所以我想“嗯jquery肯定加载了。它实际上加载了两次。但是当我加载两次时它不起作用。让我们谷歌一下!”。因此,如果您在 Google 上搜索如何在一页上加载 jquery 两次,您会看到很多答案说要使用 noconflict()。在 jquery 行之后添加它似乎可以解决问题。
关于jquery - 在 R Shiny 中使用 jQuery 时 Plotly 消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34340632/