Search code examples
rconvex-hull

How to create a convex area (connected by lines) after using "chull" on R


From a big Dataframe with info from tennis players, I created a df with only backhand shots from a single player, which includes columns with names, age and "x,y" coordinates of where the shots where taken. I already made a graphic with the tennis court and the places where the shots where taken, but I´m having a hard time creating the convex hull.

To create the first graphic I used:

Grph <- ggplot() +
  geom_point(BH, mapping = aes(x = x1 - 58.015,y = y1,
             fill = factor(BH$Result)), shape = 21, size = 5) + 
  guides(fill = guide_legend(title = NULL)) +
....

then I tried:

BHF <- chull(BH)

and I get numbers, but can´t make the graphic with the outter lines.

What follows is not making sense to me (yeah, I´m new to this):

X <- matrix(stats::rnorm(2000), ncol = 2)
chull(X)
plot(X, cex = 0.5)
hpts <- chull(X)
hpts <- c(hpts, hpts[1])
lines(X[hpts, ])

Some of the subsets I used are:

data_B1 <- subset(full_data, Player == ch_player & Opp == 
ch_opp &Local == match & Type == event1)
data_B2 <- subset(full_data, Player == ch_player & Opp == ch_opp
&Local == match & Type == event2)

after creating the substes I used rbind to create the BH DF

event1 are defensive backhands event2 are offensive backhands


Solution

  • BH = data.frame(x = rnorm(2000), y= rnorm(2000))  # create a dummy example data.frame
    BHL = chull(BH[, c("x", "y")]) # calculate convex hull for x and y columns
    BHL = c(BHL, BHL[1]) # add the first point again at the end, so the path loops back to the beginning
    
    #now plot using geom_path 
    ggplot(BH, aes(x,y)) +
      geom_point() +
      geom_path(data=BH[BHL, ])
    

    enter image description here