正确地在Shiny中渲染图,只有多个图中的一个渲染

时间:2018-12-17 16:25:22

标签: r shiny ggplotly

将以下代码作为app.r运行会在闪亮的应用程序中为p2进行ggplotly渲染,但不会p1进行渲染,尽管p1确实在RStudio绘图窗格中进行渲染。我希望能够在应用程序和Shiny上获得p1p2的绘图。我想念什么?

library(shiny)
library(plotly)
library(ggplot2)

x <- seq(1:100)
y <- rnorm(100)
df <- data.frame(x,y)

p1 <- ggplot(df, aes(x,y)) + geom_line()
p2 <- ggplot(df, aes(x,y)) + geom_point()


ui <- fluidPage(
            fluidRow(
              column(width=8,
                     radioButtons("radioInput", "Radio Button Header", choices =
                                    c("name of plot 1 for user" = "plot 1",
                                      "name of plot 2 for user" = "plot 2"
                                  )   )
                    )
            ),             
            plotlyOutput("distPlot", height="700px")
)

server <- function(input, output) {

output$distPlot <- renderPlotly({

if (input$radioInput == "plot 1")  {
  p1 <- ggplotly(p1)
  print(p1)}   
if (input$radioInput == "plot 2")  {
  p2 <- ggplotly(p2)
  print(p2)}  

 })
}  

shinyApp(ui = ui, server = server)

如果没有plotly(删除ggplotly呼叫并将plotlyOutput改回plotOutput,而将renderPlotly改回renderPlot),则Shiny会同时绘制:

library(shiny)
library(plotly)
library(ggplot2)

x <- seq(1:100)
y <- rnorm(100)
df <- data.frame(x,y)

p1 <- ggplot(df, aes(x,y)) + geom_line()
p2 <- ggplot(df, aes(x,y)) + geom_point()


ui <- fluidPage(
fluidRow(
column(width=8,
       radioButtons("radioInput", "Radio Button Header", choices =
                      c("name of plot 1 for user" = "plot 1",
                        "name of plot 2 for user" = "plot 2"
                      )   )
 )
),             
 plotOutput("distPlot", height="700px")
)

server <- function(input, output) {

output$distPlot <- renderPlot({

if (input$radioInput == "plot 1")  {

  print(p1) }   
if (input$radioInput == "plot 2")  {

  print(p2)}  

})
}  

shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

您缺少else if

library(shiny)
library(plotly)
library(ggplot2)

x <- seq(1:100)
y <- rnorm(100)
df <- data.frame(x,y)

p1 <- ggplot(df, aes(x,y)) + geom_line()
p2 <- ggplot(df, aes(x,y)) + geom_point()


ui <- fluidPage(
  fluidRow(
    column(width=8,
           radioButtons("radioInput", "Radio Button Header", choices =
                          c("name of plot 1 for user" = "plot 1",
                            "name of plot 2 for user" = "plot 2"
                          )   )
    )
  ),             
  plotlyOutput("distPlot", height="700px")
)

server <- function(input, output) {

  output$distPlot <- renderPlotly({

    if (input$radioInput == "plot 1")  {
      p1 <- ggplotly(p1)
      print(p1) }   
    else if (input$radioInput == "plot 2")  {
      p2 <- ggplotly(p2)
      print(p2)}  

  })
}  

shinyApp(ui = ui, server = server)