Skip to content

Instantly share code, notes, and snippets.

@Rekyt
Last active November 6, 2017 22:13
Show Gist options
  • Save Rekyt/40b2af30c6e27300c3ba to your computer and use it in GitHub Desktop.
Save Rekyt/40b2af30c6e27300c3ba to your computer and use it in GitHub Desktop.
Draw convex hull for points in ggplot2
# Script to plot convex hull over points in ggplot2
# Packages
library(dplyr) # To make code easier to read
library(ggplot2)
# Data Generation
set.seed(1) # For reproducibility of example
df = data.frame(x = rnorm(100, 10, 5), y = rnorm(100, 10, 5), z = sample(letters[1:5], size = 100, replace = T))
# Plot without convex hulls
p = ggplot(df, aes(x, y, colour = z)) +
geom_point()
# Computing convex hulls
s = df %>%
split(df$z) # Tranform data.frame in lists of data.frames depending on column 'z'
ch = s %>%
# Compute which points are on the convex hull of each data.frame /!\ Check how 'chull' works
lapply(., function(el) chull(el$x, el$y)) # 'ch' now contains the row numbers of points on convex hull per sub-data.frame
# Get points for each sub-data.frame using names index
ch = lapply(names(ch), function(x) s[[x]][ch[[x]],]) %>%
do.call(rbind, .) # Join all convex hull points in a single data.frame
# Plot with convex hulls
p.ch = ggplot(df, aes(x, y, colour = z)) +
geom_point() +
geom_polygon(data = ch, aes(fill = z), alpha = 0.2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment