2015-12-17 25 views
2

我正在使用jQuery (jQuery Core 2.1.4)開發我的Shiny應用程序的一部分。另外,我正在使用新的plotly包來渲染圖。 jQuery自己也完美工作,並且plotly也是;然而,當使用兩者時,來自plotly的地塊消失。調用jQuery似乎是原因。當在R中使用jQuery時Plotly消失

是否有變通,允許在同一個閃亮的應用程序使用jQuery和plotly (特別ggplotly)?

這裏是一個例子。我知道這個例子不需要jQuery的,但只是爲了說明plotly情節如何dissapear包括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)) 

謝謝!

+0

「但只是爲了說明如何陰謀詭計消失」......你是什麼意思?當我運行你的代碼,我得到了陰謀...... – MLavoie

+0

@MLavoie取消註釋行#標籤$頭(標籤$ script(src ='http://code.jquery.com/jquery-2.1.4.js' )),然後你就會消失(至少在R的瀏覽器和Chrome中) –

+0

請看我的解決方案。還有什麼你期望的? –

回答

3

解決方案:您需要使用JQuery的noconflict()。在之後加入tags$head(tags$script("$.noConflict(true);")),加載jquery的行。

說明:JQuery已經默認由Shiny加載。您可以通過查看任何Shiny應用程序的頁面來源來查看,並且您會看到它加載了jquery。當我運行你的應用程序並查看JavaScript控制檯中的錯誤時,我遇到了一些奇怪的錯誤,表明JQuery的某些功能無法正常工作。所以我認爲「hmm jquery肯定是加載的,實際上加載了兩次,但是當我加載兩次時它不工作,讓我們Google吧!」因此,如果Google爲如何在一個頁面上加載jquery兩次,您會看到很多回答說使用noconflict()。在你的jquery這行後面添加它似乎有訣竅。