识别散点图中矩形内的点

时间:2015-12-16 09:45:54

标签: r shiny ggvis

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

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

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

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")

2 个答案:

答案 0 :(得分:2)

您(可能)正在寻找的plot_brush - shiny包的功能(您可以在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)

Shiny App

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

使用和扩展第1部分,我们识别点并将它们加载到名为res的data.frame中,然后将它们加载到数据表中(使用&#39; DT&#39; -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)

这样的内容如下:Final App

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

答案 1 :(得分:1)

以下是使用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

enter image description here