识别散点图中矩形内的点

Identify points within a rectangle in a scatterplot

我有一个小的 R 脚本,它在一个逗号分隔的文件中加载数据并将其显示为散点图。我还可以通过将鼠标悬停在散点图中的各个兴趣点上来识别它们。这很酷,但我还想要在散点图中的一个区域上绘制一个矩形,并获得一个包含该矩形内数据点 ID 的列表。 (这的最终目标是一个闪亮的应用程序)。

即我该怎么做才能 a) 绘制一个矩形,b) 获取该矩形内的点以及 c) 以可以复制和粘贴的形式为最终用户显示该列表?

这是一个工作示例(使用 mtcars 而不是 y csv 文件):

library(ggvis)
mtc <- mtcars
mtc$id <- 1:nrow(mtc)

all_values <- function(x) {
  if(is.null(x)) return(NULL)
  row <- mtc[mtc$id == x$id, ]
  paste0(names(row), ": ", format(row), collapse = "<br />")
}

mtc %>% ggvis(x = ~wt, y = ~mpg, key := ~id) %>%
  layer_points() %>%
  add_tooltip(all_values, "hover")

您(可能)正在寻找的是 shiny 包的 plot_brush 函数(您可以在 Shiny Gallery 中找到示例)。

以下将提供 2 个相互叠加的应用程序来回答您的 3 个问题:

1 用plot_brush画一个矩形

这可以通过以下代码实现:

library(shiny)

server <- function(input, output) {
  # render the plot
  output$plot1 <- renderPlot({
    plot(mtcars$mpg, mtcars$disp)
  })
  
  # set the options for the brush technique
  output$plotui <- renderUI({
    plotOutput("plot1", height=300,
               brush = brushOpts(id = "plot_brush")
    )
  })
}

ui <- fluidPage(
  # render the plot
  uiOutput("plotui")
)

# run the app
shinyApp(ui = ui, server = server)

2 & 3 识别点并打印数据表

使用和扩展第 1 部分,我们识别点并将它们加载到名为 res 的 data.frame 中,然后将它们加载到数据表中(使用 'DT'-package):

library(shiny)
library(DT)

server <- function(input, output) {
  # render the plot
  output$plot1 <- renderPlot({
    plot(mtcars$mpg, mtcars$disp)
  })
  
  # set the options for the brush technique
  output$plotui <- renderUI({
    plotOutput("plot1", height=300,
               brush = brushOpts(id = "plot_brush")
    )
  })
  
  # for part 2 and 3
  output$plot_brushed_points <- renderDataTable({
    df <- mtcars
    # this function gets the data for you
    res <- brushedPoints(df, input$plot_brush, "mpg","disp") 
    # mpg = name of x variable, disp = name of y variable
    
    # puts the results in a datatable format
    datatable(res)
  })
}

ui <- fluidPage(
  # render the plot
  uiOutput("plotui"),
  # renders the datatable
  dataTableOutput("plot_brushed_points")
)

# run the app
shinyApp(ui = ui, server = server)

这给出了这样的东西:

Whosebug 上的这个问题将为您指明鼠标悬停的正确方向。

这是一个使用 locator() 函数的简单示例:

# function
loc.box <- function(x,y){
  print("choose bottom left corner")
  p1 <- locator(1)
  print("choose top right corner")
  p2 <- locator(1)
  rect(p1$x, p1$y, p2$x, p2$y, border=3, col=rgb(0,1,0,0.1))
  incl <- which(
    x >= p1$x &
    x <= p2$x &
    y >= p1$y &
    y <= p2$y
  )
  return(incl)
}

# data
set.seed(1)
n <- 100
x <- runif(n)
y <- runif(n)

# plot and select
op <- par(ps=9, mar=c(4,4,1,1))
plot(x, y, pch=20, cex=0.3)
text(x, y, labels=seq(x), pos=3)
par(op)
res <- loc.box(x,y)
res
# [1]  2  8 14 19 23 26 31 36 40 42 51 53 63 75