Voronoi Diagrams in Plotly and R

Here’s a function which uses plotly’s R Library to overlay a voronoi diagram on top of a 2-D K-Means visualization.

Visit the Getting Started section to get Plotly up and running using R.

Here’s a quick rundown on how this function works:

  • Accepts a data frame containing x and y coordinates of a bunch of data points
  • The dataframe must have a cluster column specifying the k-means cluster to which point belongs to
  • The function uses the deldir package to compute the Voronoi tesselation
  • The function then uses some co-ordinate geometry to create the final visualization using plot_ly
  • If interested, set the parameter print.ggplot to TRUE to see a diagnostic intermediary plot
  • Try modifying the n.sd.x and n.sd.y parameters to adjust x-axis and y-axis limits

Note that this is more of a hack and I am sure there are better more elegant ways to do this. If you have suggestions let us know !

Function definition

Function call

Another example