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