首页 > 解决方案 > 为什么 Boxplot 出现在 RStudio 而不是我的 Shiny 应用程序中?

问题描述

我有以下代码。我的 Shiny 应用程序中正确显示了三个图(第 1、第 2、第 4 个),而缺少第 3 个图,即“箱线图”。但是它出现在 RStudio 的绘图窗口中。我究竟做错了什么?

library(shiny)

ui <- fluidPage(

    fluidRow( 
        verticalLayout( 
            splitLayout(cellWidths = c("50%", "50%"), 
                        plotOutput("pt1"), 
                        plotOutput("pt2")), 
            splitLayout(cellWidths = c("50%", "50%"), 
                        plotOutput("pt3"), 
                        plotOutput("pt4"))
        )
    )
)

server <- function(input, output) {

    set.seed(1234)

    pt1 <- qplot(rnorm(600),fill=I("blue"),binwidth=0.2)
    pt2 <- qplot(rnorm(200),fill=I("blue"),binwidth=0.2)
    pt3 <- boxplot(mpg~cyl,data=mtcars, main="Cars", xlab="cyl", ylab="mpg") 
    pt4 <- qplot(rnorm(900),fill=I("blue"),binwidth=0.2)

    output$pt1 = renderPlot({pt1})
    output$pt2 = renderPlot({pt2})
    output$pt3 = renderPlot({pt3})
    output$pt4 = renderPlot({pt4})    

}

shinyApp(ui = ui, server = server)

标签: rplotshiny

解决方案


正如您在此处看到的:如何将箱线图保存为变量?我们需要一个小技巧来将箱线图保存为变量。

library(shiny)
library(ggplot2)
ui <- fluidPage(

  fluidRow( 
    verticalLayout( 
      splitLayout(cellWidths = c("50%", "50%"), 
                  plotOutput("pt1"), 
                  plotOutput("pt2")), 
      splitLayout(cellWidths = c("50%", "50%"), 
                  plotOutput("pt3"), 
                  plotOutput("pt4"))
    )
  )
)

server <- function(input, output) {

  set.seed(1234)

  pt1 <- qplot(rnorm(600),fill=I("blue"),binwidth=0.2)
  pt2 <- qplot(rnorm(200),fill=I("blue"),binwidth=0.2)
  boxplot(mpg~cyl,data=mtcars, main="Cars", xlab="cyl", ylab="mpg")
  pt3 = recordPlot()
  dev.off()

  pt4 <- qplot(rnorm(900),fill=I("blue"),binwidth=0.2)

  output$pt1 = renderPlot({pt1})
  output$pt2 = renderPlot({pt2})
  output$pt3 = renderPlot({pt3 })
  output$pt4 = renderPlot({pt4})    

}

shinyApp(ui = ui, server = server)

推荐阅读