Search code examples
rggplot2dplyrgeom

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


I have a scatter plot:

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)

I want to count how many points are in each of the rectangles. And depending on the color of the point, I want to give them values. ex: blue(0), green(1).

How can I do this?


Solution

  • If you know the range for each variable in advance (which it seems like you do based on the xmin / ymin args you have), then I would do annotation first.

    You don't have a scatterplot, you have data you are representing as a scatterplot, and you want to annotate the points so that they display as different colors on the scatterplot.

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

    enter image description here