Filtering by an Area

Hi, I believe I have asked a similar question to this before, but this question has a few more parameters. I was wondering if someone can help me filter the data points by saying if it is the zone or not in the zone.

strikezone <- data.frame(
x = c(-0.95, 0.95, 0.95, -0.95, -0.95),
z = c(1.6, 1.6, 3.5, 3.5, 1.6)
)

data <- data.frame(
plate_x = c(1.5, -0.899, -0.1, -1, -0.85, -0.85, -0.1, 0, 0.5, -0.8,
-1.01, -1.1, -0.5, -2, -0.4, -0.5, -0.61, -0.75, 0.61, 0, 0,
0.9, 0.4, -1, 1.15, 0.1, 0.2, -1.11, -0.5, -0.4),
plate_z = c(4.1, 1.61, 1.4, 2.5, 3.1, 3.2, 3.4, 2.9, 2.41, 3.15, 1.1, 1.6,
1.72, 2.1, 2.4, 3, 2, 3.75, 1.91, 2, 2.8, 1.6, 2.5, 1.6, 1.5,
3, 1.6, 1.4, 2.5, 1.9)
)

ggplot()+geom_path(data=strikezone, aes(x=x, y=z))+coord_equal()+xlim(-1,1)+ylim(1,4)

zonebase

Thank you!

Are you looking for something like this?

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)

strikezone <- data.frame(x = c(-0.95, 0.95, 0.95, -0.95, -0.95),
                         z = c(1.6, 1.6, 3.5, 3.5, 1.6))

dataset <- data.frame(plate_x = c(1.5, -0.899, -0.1, -1, -0.85, -0.85, -0.1, 0, 0.5, -0.8, -1.01, -1.1, -0.5, -2, -0.4, -0.5, -0.61, -0.75, 0.61, 0, 0, 0.9, 0.4, -1, 1.15, 0.1, 0.2, -1.11, -0.5, -0.4),
                      plate_z = c(4.1, 1.61, 1.4, 2.5, 3.1, 3.2, 3.4, 2.9, 2.41, 3.15, 1.1, 1.6, 1.72, 2.1, 2.4, 3, 2, 3.75, 1.91, 2, 2.8, 1.6, 2.5, 1.6, 1.5, 3, 1.6, 1.4, 2.5, 1.9))

dataset %>%
    mutate(is_x_in_zone = between(x = plate_x,
                                  left = min(strikezone$x),
                                  right = max(strikezone$x)),
           is_z_in_zone = between(x = plate_z,
                                  left = min(strikezone$z),
                                  right = max(strikezone$z)),
           is_point_in_zone = is_x_in_zone & is_z_in_zone) %>%
    filter(is_point_in_zone) %>%
    qplot(x = plate_x,
          y = plate_z,
          data = .) +
    geom_path(data = strikezone,
              mapping = aes(x = x,
                            y = z)) +
    coord_equal(xlim = c(-1, 1),
                ylim = c(1, 4))

Created on 2019-10-08 by the reprex package (v0.3.0)

2 Likes

Yes, thank you for your help.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.