【问题标题】:Plotly disappears when using jQuery in R Shiny在 R Shiny 中使用 jQuery 时,Plotly 消失
【发布时间】:2018-10-09 01:38:06
【问题描述】:

我正在使用 jQuery (jQuery Core 2.1.4) 开发我的 Shiny 应用程序的一部分。此外,我正在使用新的plotly 包来渲染绘图。 jQuery 可以独立运行,plotly 也可以;但是,当同时使用两者时,来自plotly 的图消失了。调用 jQuery 似乎是原因。

是否有允许使用 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))

谢谢!

【问题讨论】:

  • “但只是为了说明情节如何消失”......你是什么意思?当我运行你的代码时,我得到了情节......
  • @MLavoie 取消#tags$head(tags$script(src='http://code.jquery.com/jquery-2.1.4.js')), 行的注释,你会发现它消失了(至少在 R 的浏览器和 Chrome 中)
  • 请看我的解决方案。你还有什么期待的吗?
  • 就是这样。谢谢! (以及解释)

标签: jquery r shiny plotly


【解决方案1】:

解决方法:你需要使用JQuery的noconflict()。在加载 jquery 的行之后添加tags$head(tags$script("$.noConflict(true);")),

解释:JQuery 已经被 Shiny 默认加载。您可以通过查看任何 Shiny 应用程序的页面源来看到这一点,您会看到它加载了 jquery。当我运行您的应用程序并查看 JavaScript 控制台是否有错误时,我收到了奇怪的错误,表明 JQuery 的某些内容无法正常工作。所以我想“嗯 jquery 肯定已经加载了。它实际上加载了两次。但是当我加载两次时它就不起作用了。让我们谷歌一下吧!”。因此,如果您在 Google 上搜索如何在一个页面上加载 jquery 两次,您会看到很多回答说要使用 noconflict()。在你的 jquery 行之后添加它似乎可以解决问题。

【讨论】:

    猜你喜欢
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 2016-09-12
    • 2017-09-18
    • 2018-08-03
    • 2021-09-25
    相关资源
    最近更新 更多