首页 > 解决方案 > 在已经渲染后将元素添加到 Shiny 中的绘图

问题描述

在我正在处理的应用程序中渲染绘图后,我想要添加 ablines 的选项,并且这些选项仍然是绘图对象的一部分,即如果 x 轴发生变化,它仍然存在。我知道我可以重新定义绘制的对象,但是由于绘图有几种不同的选项,因此此方法将不起作用,因为我将有无数不同的绘图调用,如果需要,我将无法跟踪所有这些调用改变些什么。是否有类似于 dlypr %>% 的东西可以用于闪亮的绘图,或者任何会产生相同影响的东西?

我尝试过单独运行,如下代码所示。但是,这不会在图中添加一条线。

#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(shiny)

x <- faithful[, 2] 
x2 = x

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  titlePanel("Old Faithful Geyser Data"),

  # Sidebar with a slider input for cut
  sidebarLayout(
    sidebarPanel(
      numericInput("lines",
                   "Vertical Line",
                   min = 1,
                   value = 60),
      actionButton("add", "Add?"),
      numericInput("xlimL", "Lower x", value=0),
      numericInput("xlimU", "Upper x", value=50)
    ),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("distPlot")
    )
  )
)

server <- function(input, output) {

  data <- reactiveValues(x2 = x2)

  output$distPlot <- renderPlot({
    plot(data$x2, xlim = c(input$xlimL, input$xlimU))
  })

  observeEvent(input$add,{
    abline(v = input$lines)
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

我在添加 abline 的情节之后,当我更改 x 限制时,它会保留在情节中,并且无需多次调用 renderPlot 即可执行此操作。

提前致谢!

标签: shiny

解决方案


因此,通过使数据 a 来做到这一点reactiveValue,并添加lines = NULL它可以完成,但服务器部分如下:

server <- function(input, output) {

  data <- reactiveValues(x2 = x2, lines = NULL)

  output$distPlot <- renderPlot({
    plot(data$x2, xlim = c(input$xlimL, input$xlimU))
    abline(v =  data$lines)
  })

  observeEvent(input$add,{
    data$lines = c(data$lines, input$lines)
  })
}

推荐阅读