Circle packing in R (again)

[This article was first published on Last Resort Software, 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.

Back in 2010 I posted some R code for circle packing. Now, just five years later, I’ve ported the code to Rcpp and created a little package which you can find at GitHub.

The main function is circleLayout which takes a set of overlapping circles and tries to find a non-overlapping arrangement for them. Here’s an example:

And here’s the code:

<br /># Create some random circles, positioned within the central portion<br /># of a bounding square, with smaller circles being more common than<br /># larger ones.<br /><br />ncircles <- 200<br />limits <- c(-50, 50)<br />inset <- diff(limits) / 3<br />rmax <- 20<br /><br />xyr <- data.frame(<br />  x = runif(ncircles, min(limits) + inset, max(limits) - inset),<br />  y = runif(ncircles, min(limits) + inset, max(limits) - inset),<br />  r = rbeta(ncircles, 1, 10) * rmax)<br /><br /># Next, we use the `circleLayout` function to try to find a non-overlapping<br /># arrangement, allowing the circles to occupy any part of the bounding square.<br /># The returned value is a list with elements for the layout and the number<br /># of iterations performed.<br /><br />library(packcircles)<br /><br />res <- circleLayout(xyr, limits, limits, maxiter = 1000)<br />cat(res$niter, "iterations performed")<br /><br /># Now draw the before and after layouts with ggplot<br /><br />library(ggplot2)<br />library(gridExtra)<br /><br />## plot data for the `before` layout<br />dat.before <- circlePlotData(xyr)<br /><br />## plot dta for the `after` layout returned by circleLayout<br />dat.after <- circlePlotData(res$layout)<br /><br />doPlot <- function(dat, title)<br />  ggplot(dat) + <br />  geom_polygon(aes(x, y, group=id), colour="brown", fill="burlywood", alpha=0.3) +<br />  coord_equal(xlim=limits, ylim=limits) +<br />  theme_bw() +<br />  theme(axis.text=element_blank(),<br />        axis.ticks=element_blank(),<br />        axis.title=element_blank()) +<br />  labs(title=title)<br /><br />grid.arrange(<br />  doPlot(dat.before, "before"),<br />  doPlot(dat.after, "after"),<br />  nrow=1)<br /><br />

To leave a comment for the author, please follow the link and comment on their blog: Last Resort Software.

R-bloggers.com 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)