Skip to content

Instantly share code, notes, and snippets.

@Rekyt
Created November 4, 2015 20:58
Show Gist options
  • Save Rekyt/8c3f23f9dac8e0be6e5f to your computer and use it in GitHub Desktop.
Save Rekyt/8c3f23f9dac8e0be6e5f to your computer and use it in GitHub Desktop.
Snippet to draw an alpha shape using ggplot2
# Script to plot an alpha shape on ggplot2 from a given sets of points
# Inspired by: https://rpubs.com/geospacedman/alphasimple
# Packages --------------------------------------------------------------------
library(ggplot2)
library(dplyr)
library(alphahull)
library(igraph)
# Data Generation -------------------------------------------------------------
set.seed(1001)
ex = data.frame(x = rnorm(100), y = rnorm(100))
# Computation And Order Alpha Shape -------------------------------------------
ex_ashape = ashape(ex, alpha = 1.5)
# Take the coordinates of points on the edges of the alpha shape
ex_mat = ex_ashape$edges[, c("ind1", "ind2")]
# Convert 'numeric' matrix to 'character' matrix, to avoid wrong node orders
# (Otherwise 'graph.edgelist()' interprets number as order of nodes)
class(ex_mat) = "character"
# Make the graph of points
ex_graph = graph.edgelist(ex_mat, directed = F)
# Verify its a cyclic graph
plot(ex_graph)
# Cut open the graph to walk through it in order
cut_graph = ex_graph - E(ex_graph)[1] # Cut the first edge
ends = names(which(degree(cut_graph) == 1)) # Get two nodes with degree = 1
# Compute a path
path = get.shortest.paths(cut_graph, ends[1], ends[2])$vpath[[1]]
# Get node names (= row numbers in original data.frame)
path_nodes = as.numeric(V(ex_graph)[path]$name)
# General plot ----------------------------------------------------------------
p_no_ashape = ggplot(ex, aes(x = x, y = y)) +
geom_point()
p_no_ashape
p_ashape = p_no_ashape +
geom_polygon(data = ex[path_nodes, ], fill = "purple", alpha = 0.5)
p_ashape
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment