ggplotly - 在现有情节中添加线条(闪亮)

时间:2017-08-08 13:34:35

标签: r ggplot2 shiny plotly

我想让用户在已经存在的绘图中添加第二行,或者在必要时删除它而不重绘整个绘图。唉,我不知道如何做到这一点,或者甚至可以用ggplotly来做到这一点。有没有一个包可以让你这样做?

ui.r

shinyUI(fluidPage(
  sidebarLayout(

    position = "left",

    sidebarPanel(
      selectizeInput("fund", label = NULL, selected = "", choices = c('', LETTERS[1:6]), options = list(placeholder = "Choose something"), width = "350px"),
      selectizeInput("benchmark", label = NULL, selected = "", choices = c('', NULL, letters[1:6]), options = list(placeholder = "Choose something"), width = "350px"),
      verbatimTextOutput("hover")
    ),

    mainPanel(
      plotlyOutput("tsplot")
    )


  )
))

server.r

require(ggplot2)
require(plotly)
require(shiny)

shinyServer(function(input, output) {

  # output$fundid <- renderText({
  #   print(input$fund)
  # })

  PFobj <- reactive({

    pf <- input$fund
    ts_info <- list(a = "x", b = "y")
    ts_data <- data.frame(Dat = seq(Sys.Date() - 200, Sys.Date(), 1), Val = cumsum(c(100, rnorm(200))))

    list(pf = pf, nav = ts_info, data = ts_data)

  })

  # Main plot
  observe({
    if(input$fund != '') {
      output$tsplot <- renderPlotly({
        p <- ggplot(PFobj()$data, aes(x = Dat, y = Val, group = 1, text = paste("</br>Date: ", Dat, "</br>Value: ", Val))) +
          geom_line(colour = "red")
        p <- ggplotly(p, tooltip = c("text"), type = "scatter", mode = "lines") %>% config(displayModeBar = F)
        p
      })
    }
  })

  # This should be updating the plot
  observe({
    if(input$benchmark != '') {
      output$tsplot <- renderPlotly({
        data <- PFobj()$data
        # p + geom_line(data, aes(x = Dat, y = Val, group = 1, text = paste("</br>Date: ", Dat, "</br>Value: ", Val)), colour = "black")
        # p %>% add_lines(x = data[,1], y = data[,2], color = "red")
      })
    }
  })

  output$hover <- renderPrint({
    d <- event_data("plotly_hover")
    if (!is.null(d)) {print(d); b <<- d$x}
  })

})

0 个答案:

没有答案