Ggplot:情节 - 互动 - 排除 - >防止排除点重置

时间:2016-12-07 10:26:14

标签: r ggplot2 shiny

我想在选择使用selectizeInput显示的第二个变量时防止重新设置曲线。例如,在下面的代码中,我们在selectizeInput cyl(6)中选择一个值(mtcars数据集),并从曲线中排除一个点,然后我们选择的第二个值要显示的cyl(4),因此前一个 cyl = 6 的曲线会自行重置(已被排除的点,再次出现)。

有没有办法阻止这种行为?在选择第二个变量时,排除的点保持“排除”?

示例代码:

library(ggplot2)
library(shiny)

ui <- fluidPage(
  fluidRow(
    column(width = 6,
           plotOutput("plot1", height = 350,
                      click = "plot1_click"), 
           selectizeInput("valuecyl", "Select value of cyl:", choices=unique(mtcars$cyl), multiple = TRUE))
  )
)

server <- function(input, output) {
  # For storing which rows have been excluded

  vals <- reactiveValues()
  data_df <- reactive({
    data <- mtcars
    data <- data[data$cyl %in% input$valuecyl, ]
    vals$keeprows = rep(TRUE, nrow(data))
    data
  })

  output$plot1 <- renderPlot({
    data<- data_df()
    keep    <- data[ vals$keeprows, , drop = FALSE]
    exclude <- data[!vals$keeprows, , drop = FALSE]
    print(keep)

    ggplot(keep, aes(wt,mpg,colour=as.factor(cyl))) + geom_point(data=keep) + geom_line(data=keep) +
      geom_point(data = exclude, shape = 21, fill = NA, color = "black", alpha = 0.25) 
  })

  # Toggle points that are clicked
  observeEvent(input$plot1_click, {
    data <-  data_df()
    res <- nearPoints(data, input$plot1_click, allRows = TRUE)

    vals$keeprows <- xor(vals$keeprows, res$selected_)
  })


}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:1)

此处的问题是,每次用户选择vals$keeprows中的值时,您都会覆盖rep(TRUE, nrow(data))并将其替换为selectize

您需要通过保留用户保留的行并添加来自额外选择的新行来更新keeprows变量。

为此,我稍微修改了您的代码:

  #added the data in the reactiveValues for convenience
  vals <- reactiveValues(keeprows=logical(0),data=mtcars[0,])

  #this observes the input and updates the data when the user adds a cyl value
  observeEvent(input$valuecyl,{
    #get the id (here rownames) of the points excluded by the user
    excluded_ids <- rownames(vals$data)[!vals$keeprows]

    #make the new data
    vals$data=mtcars[mtcars$cyl %in% input$valuecyl,] 

    #keep the rows that the user had not previously excluded.
    vals$keeprows = !(rownames(vals$data) %in% excluded_ids)
  })

由于我在reactiveValues中添加了数据并删除了data_df,因此您需要在代码中将data_df()替换为vals$data才能生效。