我希望使用 ggplot2 计算散点图某个区域中的点数

I am looking to count the number of points in a certain region of my scatter plot with ggplot2

我有一个散点图:

ex<- ggplot(rdr, aes(x = hb, y = iv, color = pt))+ geom_point() + 
  ylim(-20,20) + 
  xlim(-20,20) +
  annotate(geom = "rect", xmin = -10, xmax = 10, ymin = -10, ymax = 10,
           fill = "gray100", colour = "black", alpha = 0.5)  +
  annotate( geom = "rect", xmin = -10, xmax = 10, ymin = -15, ymax = -10, fill = "palegreen", color = "blue", alpha =0.5)

我想计算每个矩形中有多少个点。根据点的颜色,我想给它们赋值。例如:蓝色 (0)、绿色 (1)。

我该怎么做?

如果您事先知道每个变量的范围(看起来您是根据您拥有的 xmin / ymin args 做的),那么我会做注释 首先.

您没有散点图,您有表示为散点图的数据,并且您想要注释这些点,以便它们在散点图上显示为不同的颜色。

library(dplyr)
library(ggplot2)
data(mtcars)
mtcars2 = mtcars %>%
  mutate(good = case_when(
    # this is the annotation step
    between(hp, 100, 150) & between(mpg, 15, 20) ~ 1,
    # this says everything else gets this value
    TRUE ~ 0
))
# we need as.factor to get different colors displayed
ggplot(mtcars2, aes(x = mpg, y = hp, color = as.factor(good))) + geom_point()