-->

矩形内识别点的散点图(Identify points within a rectangle in a

2019-10-29 10:03发布

我有一个小ř脚本负载与数据并将其显示为散点图以逗号分隔的文件。 我也可以将鼠标悬停在用鼠标确定在散点图个人感兴趣点。 这是很酷,但我也想结束在散点图的区域绘制一个矩形,并取得与该矩形内的数据点的ID列表。 (这样做的最终目标是一个闪亮的应用程序)。

即我怎样才能让这个我可以一)绘制一个矩形,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")

Answer 1:

你是什么东西(可能)寻找是在plot_brush中的-functions shiny -package(你在这里找到一个例子在闪亮的画廊 )。

下面将提供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,我们确定的点,并将它们加载到一个data.frame称为res ,然后将它们加载到一个数据表(使用“DT'包):

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)

这给了这样的事情:

在这个问题上#1将指向您在鼠标悬停在正确的方向。



Answer 2:

下面是一个使用一个简单的例子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



文章来源: Identify points within a rectangle in a scatterplot
标签: r shiny ggvis