首页 > 解决方案 > R Shiny:我可以在没有 actionButton 的情况下使用 shinyjs() 吗?

问题描述

我希望使用 shinyjs() 自动隐藏绘图,而无需使用 actionButton。这可能吗?

这是我在 ui.R 中的代码:

tabPanel(title = "Plot", useShinyjs(), 
         sidebarPanel(width = 4,                                                                           
                      h2("Plotting"),                                                                           
                      radioButtons(inputId = "type",                                                                                                       
                                   label = "Type of Plot:",                                                                                                      
                                   choices = c("Scatter Plot", 
                                               "Pie Chart", "Bar Chart"),                                                                                                   
                                   selected = "Scatter Plot"),                                                                                  
                   ),

         mainPanel(width = 8,
                   br(), br(),                                                                  
                   div(id='showplot', plotlyOutput(outputId = "plot")),
                   div(id='showplot2', plotOutput(outputId = "plot2")),
                   br(),                                                     
                   h5(textOutput("description"))
                   )
                  )

这是我在 server.R 中的代码:

output$plot <- renderPlotly({
  if (input$type == "Scatter Plot") {
  show("showplot") 
} else {
  hide("showplot")
}
  ggplotly({
    p <- ggplot(data = variable_source(), aes_string(x = input$x, y = input$y)) +
    geom_point(size = input$size, col = input$color) +
    labs(x = x(),
         y = y(),
         color = toTitleCase(str_replace_all(input$z, "_", " ")),
         title = toTitleCase(input$plot_title)

  if (input$fit == TRUE) {
    p <- p + geom_smooth(method = "lm")
  }
  p
  })
})

output$plot2 <- renderPlot({
if (input$type == "Pie Chart") {
    show("showplot2") 
  } else {
    hide("showplot2")
  }
  ggplot(shortlistpied(), aes_string(x = factor(1),  y = "Percentage", fill = input$y)) + 
    geom_bar(stat = "identity", width = 1) +
    geom_text(aes(x = factor(1), y = label_pos, label = perc_text), size = 4) + 
    scale_fill_distiller(palette = "Oranges") +
    coord_polar("y") + 
    facet_wrap( ~get(input$x)) + 
    theme_void()
})

编辑:这是我在运行应用程序时首先看到的:scatter plot original,这一切都很好。但是当我点击饼图时,我看到了:饼图消失了。当它应该像这样出现时,图表就会消失:pie chart original。另外,当我返回单击散点图时,它也会像这样消失:scatter plot消失。这可以解决吗?

基本上,我要做的是让主面板在用户单击散点图时显示散点图,当用户单击饼图时显示饼图。我曾尝试使用 NULL 但参考这篇文章 - R Shiny: How not to display plot when NULL,它会产生一个不舒服的空白,我希望能够避免这种情况。

提前非常感谢!

标签: rshinyshow-hideshinyjs

解决方案


推荐阅读