Little useless-useful R functions – Interactive Voronoi diagram generator using R and x11()

[This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Yes. Finally, the Voronoi diagrams with the use of x11() function. This diagram is presentation of a plane that is partitioned every time, a user clicks on the canvas of x11. This plane is partitioned into smaller regions that are close to given set of points.

Partitioning into smaller regions or convex polygons happens in such manner that each polygon contains only one generating point and every point in a given polygon is closer to its generating point than to any other.

This is certainly very useful for many fields of computer science and programming, graphics, geoanalysis, analysis of space, meteorology and so on. And also useful for this series of useless-useful functions ?

With R we have many packages available, but this function is focused on end-user and clicking on the canvas that partitions the plane into smaller convex regions or polygons.

The useless R code is in gist only ggplot2 function that generates the voronoi diagram and function to navigate mouse clicks on x11() interface

# packages

dff <- data.frame(NULL,NULL,NULL)

#### Graph
voronoiGraphBoard <- function(){
  r <- ggplot(data=dff, aes(x=xl,y=yl)) +
    geom_segment( aes(x = x1, y = y1, xend = x2, yend = y2), size = 1, data = voronoi$dirsgs, linetype = 1, color= "orange") +
    geom_point( shape=21, size = 3, color="red", fill="blue") +

### Clicking on canvas
click <- function(DefaultGraph=voronoiGraphBoard(), steps=st){
    DefaultGraph <-
      for (n in 1:steps) { <- locator(n = 1, type = "o") 
      xl <-$x
      yl <-$y
      distance <- sqrt((xl-100)^2 + (yl-100)^2)
      df <- data.frame(xl,yl, distance)
      dff <<- rbind(dff, df)
      if (nrow(dff)>=2){
        voronoi <<- deldir(dff$xl, dff$yl)
        DefaultGraph <- voronoiGraphBoard()

#### Start with x11 
Draw_x11 <- function(st){
  DefaultGraph <<- voronoiGraphBoard()

And the rest is just running the main function:

# Generate Voronoi with defined steps

As always, code is available in at the Github in same Useless_R_function repository.

Happy R-coding!

To leave a comment for the author, please follow the link and comment on their blog: R – TomazTsql. offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)