Skip to content

Instantly share code, notes, and snippets.

@rmaia
Last active November 29, 2023 07:54
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmaia/5296401 to your computer and use it in GitHub Desktop.
Save rmaia/5296401 to your computer and use it in GitHub Desktop.
Plot convex hulls according to a factor
require(ggplot2)
require(plyr)
# make toy data
set.seed(1)
dataf <- data.frame(
x = rnorm(100),
y = c(rnorm(50,-1), rnorm(50,1)),
cat = rep(c("A","B"), each=50)
)
ggplot(data=dataf, aes(x=x, y=y, color=cat)) + geom_point()
# get convex hull coordinates
# chull function gives you which points delimit the minimum convex hull
chulls <- ddply(dataf, .(cat), function(df) df[chull(df$x, df$y), ])
# plot polygons
ggplot(data=dataf, aes(x=x, y=y, color=cat)) + geom_point() +
geom_polygon(data=chulls, aes(x=x, y=y, group=cat), fill=NA)
# if you wanna get fancy with the colors
# (will give annoying warnings if number of groups is smaller than 3, ignore)
ggplot(data=dataf, aes(x=x, y=y, color=cat)) + geom_point() +
geom_polygon(data=chulls, aes(x=x, y=y, fill=cat), alpha=0.2) +
scale_color_brewer(palette='Set1') +
scale_fill_brewer(palette='Set1')
@dmi3kno
Copy link

dmi3kno commented Oct 25, 2022

For those coming here for the code, here's the plot produced by the code above
ggplot_chulls

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment