ShinyApp技术问题:根据交互输入值绘制对应命名的Plotly图形
Hey there! I’ve dealt with this exact issue before—getting Plotly graphs to show up correctly in Shiny based on user selections can be tricky if you’re using the wrong functions. Let’s break down the solution step by step.
The Core Issue
Plotly generates interactive HTML widget objects, not standard base R plots. That means using plotOutput()/renderPlot() or trying to print()/plot() the graph won’t work. You need Shiny’s dedicated Plotly-specific functions to handle these widgets.
Working Code Example
ui.R
You’ll need to use plotlyOutput() instead of the regular plotOutput() in your UI to properly render the interactive graph:
library(shiny) library(plotly) shinyUI(fluidPage( titlePanel("Select Your Plot"), sidebarLayout( sidebarPanel( # Dropdown for user to select 0, 1, or 2 selectInput( inputId = "plot_choice", label = "Choose a plot number:", choices = c(0, 1, 2), selected = 0 ) ), mainPanel( # Plotly-specific output container plotlyOutput("displayed_plot") ) ) ))
server.R
In the server, use renderPlotly() and directly return the corresponding Plotly object. A switch() statement is perfect for matching the user’s input to the right graph:
library(shiny) library(plotly) shinyServer(function(input, output) { # Define your pre-made Plotly graphs first pl0 <- plot_ly(mtcars, x = ~mpg, y = ~wt, type = "scatter", mode = "markers") %>% layout(title = "Plot 0: MPG vs Weight") pl1 <- plot_ly(mtcars, x = ~hp, y = ~qsec, type = "bar") %>% layout(title = "Plot 1: Horsepower vs Quarter Mile Time") pl2 <- plot_ly(mtcars, x = ~cyl, type = "histogram") %>% layout(title = "Plot 2: Cylinder Count Distribution") # Render the selected graph output$displayed_plot <- renderPlotly({ # Note: selectInput returns a string, so we use "0", "1", "2" as cases switch( input$plot_choice, "0" = pl0, "1" = pl1, "2" = pl2 ) }) })
Key Notes
- Use the right functions: Always pair
plotlyOutput()in UI withrenderPlotly()in server for Plotly graphs. - Input type matters: The
selectInput()returns a string (not a number), so yourswitch()cases need to match string values like"0"instead of numeric0. - No extra calls needed: You don’t need
print(),plot(), or explicitreturn()—just return the Plotly object directly fromrenderPlotly(), and Shiny handles the rest.
This setup will reliably render the correct Plotly graph every time the user changes their selection.
内容的提问来源于stack exchange,提问作者Makoto Miyazaki

