You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ShinyApp技术问题:根据交互输入值绘制对应命名的Plotly图形

Fixing Plotly Rendering in Shiny Based on User Input

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 with renderPlotly() in server for Plotly graphs.
  • Input type matters: The selectInput() returns a string (not a number), so your switch() cases need to match string values like "0" instead of numeric 0.
  • No extra calls needed: You don’t need print(), plot(), or explicit return()—just return the Plotly object directly from renderPlotly(), 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:16:30