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

在Shiny应用中添加基于用户输入的动态垂直线

Solution: Add Dynamic Vertical Lines via User Input in Shiny

Got it, let's modify your existing Shiny app to let users input a value and add a dynamic vertical line when they click the "Go!" button. Here's the complete working code first, then I'll walk through the key changes:

library(shinydashboard)
library(ggplot2)
library(dplyr)

UI <- dashboardPage(
  dashboardHeader(title = "Dynamic Vertical Line"),
  dashboardSidebar(
    # Add a numeric input for users to specify the vertical line's x-intercept
    numericInput(
      inputId = "vline_x",
      label = "Enter X value for vertical line:",
      value = 1,  # Default value matches your original line
      min = 0,
      max = 35,
      step = 0.5
    )
  ),
  dashboardBody(
    mainPanel(
      actionButton("goButton", "Go!"),
      plotOutput("plot_timeseries")
    )
  )
)

Server <- function(input, output) {
  # Reactive value to store the user's selected x-intercept (triggered by Go button)
  selected_x <- eventReactive(input$goButton, {
    input$vline_x
  }, ignoreNULL = FALSE)  # Keep the default value on app load

  output$plot_timeseries <- renderPlot({
    ggplot(mtcars, aes(mpg, disp)) + 
      geom_point()+ 
      scale_x_continuous(limits = c(0,35)) + 
      # Use the reactive selected_x() for the vertical line
      geom_vline(xintercept = selected_x(), color = "red", linetype = "dashed")
  })
}

shinyApp(ui = UI, server = Server)

Key Changes Explained:

  • User Input Control: Added a numericInput in the sidebar where users can type or adjust the X value for the vertical line. I set bounds matching your x-axis limits (0-35) to keep things consistent.
  • Reactive Value with Button Trigger: Used eventReactive to capture the input value only when the "Go!" button is clicked. The ignoreNULL = FALSE ensures the default value (1) is used when the app first loads, so there's always a line visible.
  • Dynamic Vertical Line: Updated geom_vline to use selected_x() instead of a hardcoded 1. This pulls the reactive value that updates when the button is pressed, making the line dynamic.

If you want the line to update without needing to click the button (real-time as the user types), you can remove the eventReactive and just use input$vline_x directly in geom_vline—but since your original app has a "Go!" button, I kept that interaction flow intact.

内容的提问来源于stack exchange,提问作者Henk Straten

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:35:49