【问题标题】:How to unisolate an particular input inside an isolate() function in R shiny dashboard如何在 R 闪亮仪表板中隔离()函数内的特定输入
【发布时间】:2017-01-27 09:19:30
【问题描述】:

我正在构建一个关于选举行为的闪亮仪表板, 我有 3 个小部件:性别、地区和政治党派,用户可以选择性别或/和地区或/和政治党派,仪表板将根据选择的输入显示一个情节,我在框中放了一个单选按钮在允许用户选择堆积条形图类型的绘图中:位置=“堆栈”或“填充”,我添加了一个操作按钮和隔离()函数,以便页面上的所有输入不发送更新到服务器,直到按下按钮。但是,我希望指示堆叠条形图类型的单选按钮不被隔离:这是我使用的代码 R:

数据框

       pff <- read.table(header=TRUE, text='
                 REGION Q99 Q101
              Tunis  Nahdha Femme
              Tunis Jabha Femme
              Tunis  NidaaTounes Homme
              Tunis  Nepasvoter Femme
              Tunis  Nepasvoter Homme
              Tunis  Nepasvoter Femme
              Tunis  NidaaTounes Homme
              Tunis  Nepasvoter Homme
              Tunis        Nahdha Femme
              Tunis  NidaaTounes Femme
              Tunis           CPR Femme
              Tunis        Nahdha Femme
              Tunis        Autres Homme
              Tunis  Nepasvoter Homme
              Tunis  Nepasvoter Femme
              Tunis        Nahdha Homme
              Tunis Jabha Homme
              Tunis  Nepasvoter Femme
              Tunis        Nahdha Homme
              Tunis        Nahdha Femme
              Tunis JabhaChaabia Homme
              Tunis        Autres Femme
              Tunis  Nepasvoter Femme
              Tunis  NidaaTounes Femme
              Tunis  Nepasvoter Homme
              Tunis  NidaaTounes Femme
              Tunis  Nepasvoter Homme
              Tunis  NidaaTounes Homme
              Tunis Jabha Femme
              Tunis  NidaaTounes Homme
              Tunis        Autres Homme
              Tunis        Nahdha Femme
              Tunis        Nahdha Homme
              Tunis        Autres Femme
              Tunis Jabha Homme
              Tunis  Nepasvoter Femme
              Tunis  Nepasvoter Homme
              Tunis           CPR Femme
              Tunis        Nahdha Homme
              Tunis  Nepasvoter Femme
              Tunis  Nepasvoter Homme
              Tunis  Nepasvoter Femme
              Tunis        Nahdha Homme
              Tunis  NidaaTounes Femme
              Tunis           CPR Homme
              Tunis           CPR Femme
              Tunis  Nepasvoter Homme
              Tunis        Autres Homme
              Tunis        Nahdha Homme
              Tunis  NidaaTounes Homme
              Tunis        Nahdha Femme
              Tunis        Autres Femme
              Tunis  Nepasvoter Femme
              Ariana        Nahdha Femme
              Ariana           CPR Femme
              Ariana        Nahdha Femme
              Ariana  Nepasvoter Homme
              Ariana  NidaaTounes Homme
              Ariana           CPR Homme
              Ariana  Nepasvoter Homme
              Ariana        Nahdha Homme
              Ariana  Nepasvoter Femme
              Ariana  NidaaTounes Homme
              Ariana           CPR Homme
              Ariana  NidaaTounes Homme
              Ariana  NidaaTounes Homme
              Ariana  NidaaTounes Homme
              Ariana           CPR Femme
              Ariana        Nahdha Femme
              Ariana           CPR Femme
              Ariana        Nahdha Homme
              Ariana        Nahdha Homme
              Ariana           CPR Homme
              Ariana        Nahdha Homme
              Ariana  Nepasvoter Homme
              Ariana  NidaaTounes Homme
              Ariana  NidaaTounes Homme
              Ariana        Nahdha Homme    ')

服务器

     library(shiny)
     library(ggplot2)
     library(ggalt)
     library(dplyr)
     library(foreign)
     library(plotly)
     library(scales)

     shinyServer(function(input, output) {
     dataa<-reactive({
     within(as.data.frame(pff), 
       Q99 <- factor(Q99, 
                     levels=names(sort(table(Q99), 
                                       decreasing=FALSE))))})
     partii2=reactive({
     filter(dataa(), Q99 %in% input$parti, REGION %in% input$region)
})
     output$plot1=renderPlotly({
     input$action
     isolate(
        if(!is.null(input$parti) && !is.null(input$region) && input$genre=="Tous"){
        if((length(input$region))==1)
         {
           g <- ggplot(partii2(), aes(x = Q99, y =(..count..)/sum(..count..)))
           g <- g + geom_bar(fill="#0f00ee") + labs(title=paste("Vote dans la région de", input$region,"pour",input$parti,sep = " ")) +labs(x="Parti politique", y="")+coord_flip()+scale_y_continuous(labels = percent)+ theme_bw()+theme(panel.border = element_rect(colour = "white"))
           }
      else{
        g <- ggplot(dataa(), aes(x = REGION, y =(..count..)/1200, fill=Q99))
        g <- g + geom_bar(position=input$position) + labs(title="vote") +labs(x=" ", y=" ")+labs(fill="Parti Politique")+scale_y_continuous(labels = percent)+ theme_bw()+theme(panel.border = element_rect(colour = "white"))  +coord_flip() + geom_text(aes( label = scales::percent(round((..count..)/1200,3 )),y=(..count..)/1200 ),stat= "count", size=4, position = "stack")

         }
        }
       )
     })
   })

Ui

  library(shiny)
  library(shinydashboard)
  library(foreign)
  library(plotly)


  shinyUI(dashboardPage(skin = "blue",
                  dashboardHeader(title = h4("Élections",style = "color:white"),

                                  titleWidth = 300 
                  ),
                  dashboardSidebar(id="", 
                                   tags$head(
                                     tags$script(
                                       HTML(
                                         "
                                         $(document).ready(function(){
                                         // Bind classes to menu items, easiet to fill in manually
                                         var ids = ['Enquête','dashboard','Prédiction','Données','Échantillon'];
                                         for(i=0; i<ids.length; i++){
                                         $('a[data-value='+ids[i]+']').addClass('my_subitem_class');
                                         }

                                         // Register click handeler
                                         $('.my_subitem_class').on('click',function(){
                                         // Unactive menuSubItems
                                         $('.my_subitem_class').parent().removeClass('active');
                                         })
                                         })
                                         "
                                       )
                                     )),
                                   sidebarMenu(
                                     menuItem(h4(strong("Enquête")), tabName = "Enquête",
                                              menuSubItem("Données",tabName = "Données"),
                                              menuSubItem("Échantillon",tabName = "Échantillon")),
                                     menuItem(h4(strong("Dashboard")), tabName = "dashboard"),
                                     menuItem(h4(strong("Prédiction")), tabName = "Prédiction"))

                                     ),



                  dashboardBody(
                    tabItems(
                      tabItem(tabName = "dashboard",h2("Le comportement électoral des citoyens tunisiens", align="center",style = "color:blue"),


                              fluidRow(
                                tiltle="filtre",
                                column(width=4,
                                       box(
                                         title = "Filtre",
                                         status = "primary",
                                         width = 8,
                                         solidHeader = TRUE,
                                         background="navy", 
                                         box(

                                           solidHeader = FALSE,
                                           width = 8,
                                           background = "navy" ,
                                           radioButtons("genre", "Genre", c("Homme","Femme","Tous"),"Tous")

                                         ),

                                         box(
                                           solidHeader = FALSE,
                                           width = 12,
                                           background = "navy",
                                           selectizeInput("region", label = "Région",
                                                          choices = levels(pff$REGION), 
                                                          selected = "Ariana", multiple=TRUE)


                                         ),

                                         box(
                                           solidHeader = FALSE,
                                           width = 12,
                                           background = "navy",
                                           selectizeInput("parti", label = "Parti politique",
                                                          choices = levels(pff$Q99), 
                                                          selected = "CPR", multiple=TRUE)


                                         ),
                                         box(
                                           actionButton("action","Mettre à jour!"),
                                           #submitButton("Mettre à jour!",icon("refresh")),
                                           background = "navy"


                                         )





                                       )





                                ),


                                box(
                                  solidHeader = FALSE ,width = 8,height = 500,
                                  collapsible = TRUE,align="center",
                                  radioButtons("position", "", c("fill","stack"), selected = "fill", inline = TRUE, width = NULL),
                                  plotlyOutput('plot1', height = 400,width = "100%")

                                )

                              )# end of fluidrow



                      )

                         ))))

【问题讨论】:

    标签: r shiny shinydashboard


    【解决方案1】:

    这对您有帮助吗?我稍微改变了服务器端,根据这里的这个问题:Convert ggplot object to plotly in shiny application

    此外,每次发生相关的用户交互时,服务器都会在控制台中显示输入。

    observeEvent(c(input$action,input$position), {
        output$plot1<-renderPlotly({
          getGgplot <- function(inputObj){
            g <- ggplot(data.frame())
            if(!is.null(inputObj$parti) && !is.null(inputObj$region) && inputObj$genre=="Tous"){
              # generate proper ggplot
              if((length(inputObj$region))==1)
              {
                g <- ggplot(inputObj$partii2, aes(x = Q99, y =(..count..)/sum(..count..)))
                g <- g + geom_bar(fill="#0f00ee") + labs(title=paste("Vote dans la région de", inputObj$region,"pour",inputObj$parti,sep = " ")) +labs(x="Parti politique", y="")+coord_flip()+scale_y_continuous(labels = percent)+ theme_bw()+theme(panel.border = element_rect(colour = "white"))
              }
              else{
                g <- ggplot(inputObj$dataa, aes(x = REGION, y =(..count..)/1200, fill=Q99))
                g <- g + geom_bar(inputObj$position) + labs(title="vote") +labs(x=" ", y=" ")+labs(fill="Parti Politique")+scale_y_continuous(labels = percent)+ theme_bw()+theme(panel.border = element_rect(colour = "white"))  +coord_flip() + geom_text(aes( label = scales::percent(round((..count..)/1200,3 )),y=(..count..)/1200 ),stat= "count", size=4, position = inputObj$position)
              }
            }
            return (
              g
            )
          }
          inputs <- list(
            "parti" = isolate( input$parti ),
            "region" = isolate( input$region ),
            "genre" = isolate( input$genre ),
            "position" = input$position,
            "dataa" = dataa(),
            "partii2" = partii2(
              partiArg = isolate( input$parti ),
              regionArg = isolate( input$region )
                                )
          )
          print("inputs:")
          print(str(inputs))
          g <- getGgplot(inputs)
    
          # return ggplot to ggplotly
          print(
            ggplotly(g)
          )  
        })
      })
    

    您的代码似乎还有其他一些问题,但我并不能真正弄清楚问题所在。即,当情况“流派 = Tous,地区 = Ariana 和 Parti politique = CPR, JabhaChaabia”时,我收到以下警告:

    Warning in if (nchar(p$labels$title %||% "") > 0) { :
    the condition has length > 1 and only the first element will be used
    

    所以这是我的综合代码,你说呢?

    library(shiny)
    library(shinydashboard)
    library(ggplot2)
    library(ggalt)
    library(dplyr)
    library(foreign)
    library(plotly)
    library(scales)
    
    pff <- read.table(header=TRUE, text='
                     REGION Q99 Q101
                      Tunis  Nahdha Femme
                      Tunis Jabha Femme
                      Tunis  NidaaTounes Homme
                      Tunis  Nepasvoter Femme
                      Tunis  Nepasvoter Homme
                      Tunis  Nepasvoter Femme
                      Tunis  NidaaTounes Homme
                      Tunis  Nepasvoter Homme
                      Tunis        Nahdha Femme
                      Tunis  NidaaTounes Femme
                      Tunis           CPR Femme
                      Tunis        Nahdha Femme
                      Tunis        Autres Homme
                      Tunis  Nepasvoter Homme
                      Tunis  Nepasvoter Femme
                      Tunis        Nahdha Homme
                      Tunis Jabha Homme
                      Tunis  Nepasvoter Femme
                      Tunis        Nahdha Homme
                      Tunis        Nahdha Femme
                      Tunis JabhaChaabia Homme
                      Tunis        Autres Femme
                      Tunis  Nepasvoter Femme
                      Tunis  NidaaTounes Femme
                      Tunis  Nepasvoter Homme
                      Tunis  NidaaTounes Femme
                      Tunis  Nepasvoter Homme
                      Tunis  NidaaTounes Homme
                      Tunis Jabha Femme
                      Tunis  NidaaTounes Homme
                      Tunis        Autres Homme
                      Tunis        Nahdha Femme
                      Tunis        Nahdha Homme
                      Tunis        Autres Femme
                      Tunis Jabha Homme
                      Tunis  Nepasvoter Femme
                      Tunis  Nepasvoter Homme
                      Tunis           CPR Femme
                      Tunis        Nahdha Homme
                      Tunis  Nepasvoter Femme
                      Tunis  Nepasvoter Homme
                      Tunis  Nepasvoter Femme
                      Tunis        Nahdha Homme
                      Tunis  NidaaTounes Femme
                      Tunis           CPR Homme
                      Tunis           CPR Femme
                      Tunis  Nepasvoter Homme
                      Tunis        Autres Homme
                      Tunis        Nahdha Homme
                      Tunis  NidaaTounes Homme
                      Tunis        Nahdha Femme
                      Tunis        Autres Femme
                      Tunis  Nepasvoter Femme
                      Ariana        Nahdha Femme
                      Ariana           CPR Femme
                      Ariana        Nahdha Femme
                      Ariana  Nepasvoter Homme
                      Ariana  NidaaTounes Homme
                      Ariana           CPR Homme
                      Ariana  Nepasvoter Homme
                      Ariana        Nahdha Homme
                      Ariana  Nepasvoter Femme
                      Ariana  NidaaTounes Homme
                      Ariana           CPR Homme
                      Ariana  NidaaTounes Homme
                      Ariana  NidaaTounes Homme
                      Ariana  NidaaTounes Homme
                      Ariana           CPR Femme
                      Ariana        Nahdha Femme
                      Ariana           CPR Femme
                      Ariana        Nahdha Homme
                      Ariana        Nahdha Homme
                      Ariana           CPR Homme
                      Ariana        Nahdha Homme
                      Ariana  Nepasvoter Homme
                      Ariana  NidaaTounes Homme
                      Ariana  NidaaTounes Homme
                      Ariana        Nahdha Homme    ')
    
    dataa<-function(){
      return (
        within(as.data.frame(pff), 
               Q99 <- factor(Q99, 
                             levels=names(sort(table(Q99), 
                                               decreasing=FALSE)))
        )
      )
    }
    
    partii2<-function(partiArg,regionArg){
      return(
        filter(dataa(), Q99 %in% partiArg, REGION %in% regionArg)
             )
    }
    
    server <- shinyServer(function(input, output) {
      observeEvent(c(input$action,input$position), {
        output$plot1<-renderPlotly({
          getGgplot <- function(inputObj){
            g <- ggplot(data.frame())
            if(!is.null(inputObj$parti) && !is.null(inputObj$region) && inputObj$genre=="Tous"){
              # generate proper ggplot
              if((length(inputObj$region))==1)
              {
                g <- ggplot(inputObj$partii2, aes(x = Q99, y =(..count..)/sum(..count..)))
                g <- g + geom_bar(fill="#0f00ee") + labs(title=paste("Vote dans la région de", inputObj$region,"pour",inputObj$parti,sep = " ")) +labs(x="Parti politique", y="")+coord_flip()+scale_y_continuous(labels = percent)+ theme_bw()+theme(panel.border = element_rect(colour = "white"))
              }
              else{
                g <- ggplot(inputObj$dataa, aes(x = REGION, y =(..count..)/1200, fill=Q99))
                g <- g + geom_bar(inputObj$position) + labs(title="vote") +labs(x=" ", y=" ")+labs(fill="Parti Politique")+scale_y_continuous(labels = percent)+ theme_bw()+theme(panel.border = element_rect(colour = "white"))  +coord_flip() + geom_text(aes( label = scales::percent(round((..count..)/1200,3 )),y=(..count..)/1200 ),stat= "count", size=4, position = inputObj$position)
              }
            }
            return (
              g
            )
          }
          inputs <- list(
            "parti" = isolate( input$parti ),
            "region" = isolate( input$region ),
            "genre" = isolate( input$genre ),
            "position" = input$position,
            "dataa" = dataa(),
            "partii2" = partii2(
              partiArg = isolate( input$parti ),
              regionArg = isolate( input$region )
                                )
          )
          print("inputs:")
          print(str(inputs))
          g <- getGgplot(inputs)
    
          # return ggplot to ggplotly
          print(
            ggplotly(g)
          )  
        })
      })
    })
    ui <- shinyUI(dashboardPage(skin = "blue",
                                dashboardHeader(title = h4("Élections",style = "color:white"),
                                                titleWidth = 300 
                                ),
                                dashboardSidebar(id="", 
                                                 tags$head(
                                                   tags$script(
                                                     HTML(
                                                       "
                                                       $(document).ready(function(){
                                                       // Bind classes to menu items, easiet to fill in manually
                                                       var ids = ['Enquête','dashboard','Prédiction','Données','Échantillon'];
                                                       for(i=0; i<ids.length; i++){
                                                       $('a[data-value='+ids[i]+']').addClass('my_subitem_class');
                                                       }
                                                       // Register click handeler
                                                       $('.my_subitem_class').on('click',function(){
                                                       // Unactive menuSubItems
                                                       $('.my_subitem_class').parent().removeClass('active');
                                                       })
                                                       })
                                                       "
                                                     )
                                                   )),
                                                 sidebarMenu(
                                                   menuItem(h4(strong("Enquête")), tabName = "Enquête",
                                                            menuSubItem("Données",tabName = "Données"),
                                                            menuSubItem("Échantillon",tabName = "Échantillon")),
                                                   menuItem(h4(strong("Dashboard")), tabName = "dashboard"),
                                                   menuItem(h4(strong("Prédiction")), tabName = "Prédiction"))
                                                   ),
                                dashboardBody(
                                  tabItems(
                                    tabItem(tabName = "dashboard",h2("Le comportement électoral des citoyens tunisiens", align="center",style = "color:blue"),
                                            fluidRow(
                                              tiltle="filtre",
                                              column(width=4,
                                                     box(
                                                       title = "Filtre",
                                                       status = "primary",
                                                       width = 8,
                                                       solidHeader = TRUE,
                                                       background="navy", 
                                                       box(
                                                         solidHeader = FALSE,
                                                         width = 8,
                                                         background = "navy" ,
                                                         radioButtons("genre", "Genre", c("Homme","Femme","Tous"),"Tous")
                                                       ),
                                                       box(
                                                         solidHeader = FALSE,
                                                         width = 12,
                                                         background = "navy",
                                                         selectizeInput("region", label = "Région",
                                                                        choices = levels(pff$REGION), 
                                                                        selected = "Ariana", multiple=TRUE)
                                                       ),
                                                       box(
                                                         solidHeader = FALSE,
                                                         width = 12,
                                                         background = "navy",
                                                         selectizeInput("parti", label = "Parti politique",
                                                                        choices = levels(pff$Q99), 
                                                                        selected = "CPR", multiple=TRUE)
                                                       ),
                                                       box(
                                                         actionButton("action","Mettre à jour!"),
                                                         #submitButton("Mettre à jour!",icon("refresh")),
                                                         background = "navy"
                                                       )
                                                     )
                                              ),
                                              box(
                                                solidHeader = FALSE ,width = 8,height = 500,
                                                collapsible = TRUE,align="center",
                                                radioButtons("position", "", c("fill","stack"), selected = "fill", inline = TRUE, width = NULL),
                                                plotlyOutput('plot1', height = 400,width = "100%")
                                              )
                                            )# end of fluidrow
                                    )
                                  ))))
    shinyApp(server = server, ui = ui)
    

    【讨论】:

    • 输入反应现在按您的要求工作。我决定使用observeEvent() 并隔离数据输入(请检查服务器控制台消息)。我不确定绘图虽然,请努力,不应该太难。 :)
    • 非常感谢@nilsole,它正在工作,但它比我想象的要复杂,实际上我的仪表板比我有大约 14 个图更复杂,每个图有大约 50 行代码,所以很难介绍所有这些变化:(我只是做了一个小例子。我可以把所有不同图的renderPlotly放在同一个observeEvent函数中吗?
    • 是的,当然可以。 :) 只是路由和存储的问题。如您所见,我将几个输入放入 observeEvent 函数中。例如,您可以插入更多内容并仅更新受影响的输出。 :)
    • 好的,非常感谢:))) @nilsole 这需要很长时间,因为我有大约 3000 行代码,但我会尝试 :D
    【解决方案2】:

    如果你检查g$labels,你会看到什么?

    您似乎允许对输入部分进行多项选择。

    标题的粘贴语句很可能会选择这些并为您提供多个标题,这就是错误的说明。

    您可以通过使用collapse="," 将部分向量包装在附加的粘贴语句中或通过使用collapse=" " 将所有输入粘贴到原始向量c("My title is",c(1,2)) 中来使部分向量成为一个字符。

    labs(title=paste("Vote dans la région de", inputObj$region,"pour",paste(inputObj$parti,collapse=","),sep = " "))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-06
      • 2017-08-17
      • 2015-04-22
      • 2020-07-17
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多