jquery - 在 R Shiny 中使用 jQuery 时 Plotly 消失

标签 jquery r shiny plotly

我正在使用jQuery (jQuery Core 2.1.4)开发我的 Shiny 应用程序的一部分。此外,我正在使用新的 plotly 包来渲染绘图。 jQuery 本身可以完美地工作,而且 plotly 也可以完美地工作;但是,当同时使用两者时,plotly 中的绘图就会消失。调用 jQuery 似乎是原因。

Is there a work-around that allows to use jQuery and plotly (specifically ggplotly) 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/

相关文章:

javascript - 日期时间选择器不起作用

javascript - 如何创建一个将答案标记为已接受的系统?

javascript - 重定向到新的 HTML 页面后隐藏 div

R 中数据帧的回归循环

r - 如何将arules apriori输出转换为R中的数据帧

r - 为什么这个 Shiny 的应用程序不使用 RStudio 显示数据帧?

javascript - 需要有关 AJAX 表单处理小部件的帮助

R dplyr在分组后在两行之间划分

r - 如何在 Ui 中返回服务器对象?

r - Shiny 的模块 : Accessing and changing reactiveValues situated inside module`s server function from the outside?