此标题已编辑 - Plotting in shinyApp。代码不生成任何图

This title has been edited- Plotting in shinyApp. Code not generating any plots

我正在尝试在同一个 shiny window 中创建多个绘图。不确定我做错了什么。它抛出一个错误,提示我的主面板出现问题。

我尝试了一些不同的方法,但似乎没有任何效果。顺便说一句,这是迈克对这个问题的回答的改编

library(ggplot2)
library(gridExtra)
library(shiny)

ui <- fluidPage(
  titlePanel("title panel"),
  sidebarLayout(position = "left",
                sidebarPanel("sidebar panel",
  checkboxInput("donum1", "plot1", value = T),
  checkboxInput("donum2", "plot2", value = F),
  checkboxInput("donum3", "plot3", value = F)
),
  mainPanel("main panel", outputplot="myPlot")))

server <- function(input, output, session) {
  
  Feature_A <- c(1, 2,1, 4,2)
  Feature_B <- c(4,5,6,6,6)
  Feature_C <- c(22,4,3,1,5)
  df<- data.frame(Feature_A ,Feature_B ,Feature_C)
  
  pt1 <- reactive({
    if (!input$donum1) return(NULL)
  p1<-ggplot(data=df, aes(Feature_A))+ geom_histogram()
  })
  pt2 <- reactive({
    if (!input$donum2) return(NULL)
  p2<-ggplot(data=df, aes(Feature_B))+ geom_histogram()
  })
  pt3 <- reactive({
    if (!input$donum3) return(NULL)
  p3<-ggplot(data=df, aes(Feature_C))+ geom_histogram()
  })
  
  output$myPlot = renderPlot({
    grid.arrange(p1, p2, p3, ncol=2,top="Main Title")
  })
  
}

shinyApp(ui, server)

编辑:

感谢 YBS 在下面的评论,我已经能够弄清楚上述问题并对上面的代码进行了更改。但是代码没有生成任何情节。有人可以帮忙吗!

mainPanel() 调用嵌套不正确。它前面需要一个逗号,因为它是 sidebarLayout() 的参数(这又是 fluidPage().

的参数
ui <- fluidPage(
  titlePanel("title panel"),
  sidebarLayout(
    position = "left",
    sidebarPanel(
      "sidebar panel",
      checkboxInput("donum1", "plot1", value = T),
      checkboxInput("donum2", "plot2", value = F),
      checkboxInput("donum3", "plot3", value = F)
    ),
    mainPanel("main panel", outputplot="myPlot")
  )
)

我喜欢使用 indention/tab 级别来更清楚地显示嵌套结构。它帮助我发现错误。

在你的第二个问题之后:

我不确定你想要将它带到你给出的例子的多远。我看到的最重要的区别是您不会从 pt1pt2pt3 返回任何内容。删除分配部分(例如p1<-)。

server <- function(input, output, session) {
  Feature_A <- c(1, 2,1, 4,2)
  Feature_B <- c(4,5,6,6,6)
  Feature_C <- c(22,4,3,1,5)
  df<- data.frame(Feature_A ,Feature_B ,Feature_C)
  
  pt1 <- reactive({
    if (!input$donum1) return(NULL)
    ggplot(data=df, aes(Feature_A))+ geom_histogram()
  })
  pt2 <- reactive({
    if (!input$donum2) return(NULL)
    ggplot(data=df, aes(Feature_B))+ geom_histogram()
  })
  pt3 <- reactive({
    if (!input$donum3) return(NULL)
    ggplot(data=df, aes(Feature_C))+ geom_histogram()
  })
  
  output$myPlot = renderPlot({
    ptlist <- list(pt1(),pt2(),pt3())
    wtlist <- c(input$wt1,input$wt2,input$wt3)
    # remove the null plots from ptlist and wtlist
    to_delete <- !sapply(ptlist,is.null)
    ptlist <- ptlist[to_delete] 
    wtlist <- wtlist[to_delete]
    if (length(ptlist)==0) return(NULL)

    grid.arrange(grobs=ptlist,widths=wtlist,ncol=length(ptlist))
  })
  
}