Search code examples
rbubble-chart

Packed Bubble Pie Charts in R?


Are there any packages in R that could help me create packed bubble charts in which the individual bubbles act as pie charts?

An example of this kind of visualization implemented in D3 was mentioned here: http://bl.ocks.org/jsl6906/4a1b818b64847fb05d56


Solution

  • You can write your own function:

    pie_bubbles<-function(xpos,ypos,radii,sectors, 
                          sector_col=NULL,main="",xlab="",ylab="") { 
      xlim<-c(min(xpos-radii),max(xpos+radii)) 
      ylim<-c(min(ypos-radii),max(ypos+radii)) 
      nbubbles<-length(xpos) 
      if(is.null(sector_col)) { 
        sector_col<-list() 
        for(scol in 1:nbubbles) 
          sector_col[[scol]]<-rainbow(length(sectors[[scol]])) 
      } 
      plot(0,xlim=xlim,ylim=ylim,type="n", 
           main=main,xlab=xlab,ylab=ylab) 
      for(bubble in 1:nbubbles) 
        floating.pie(xpos=xpos[bubble],ypos=ypos[bubble], 
                     x=sectors[[bubble]],radius=radii[bubble], 
                     col=sector_col[[bubble]]) 
    } 
    # set the x positions 
    xpos<-c(2,4,6,8,10) 
    # and the y positions 
    ypos<-c(4,8,6,10,2) 
    # the radii are the "bubble" radii 
    radii<-c(1,0.5,1.2,0.7,1.3) 
    # these are the sector extents of the pies 
    sectors<-list(1:4,c(5,3,8,6,2),c(3,2,1),c(3,7,5,8),c(2.5,3.7)) 
    # get the plotrix package 
    library(plotrix) 
    pie_bubbles(xpos,ypos,radii,sectors,main="Pie bubbles")
    

    enter image description here

    "Touching bubbles" as the OP subsequently mentioned in a comment:

    ncircles <- 200
    limits <- c(-50, 50)
    inset <- diff(limits) / 3
    rmax <- 20
    
    xyr <- data.frame(
      x = runif(ncircles, min(limits) + inset, max(limits) - inset),
      y = runif(ncircles, min(limits) + inset, max(limits) - inset),
      r = rbeta(ncircles, 1, 10) * rmax)
    
    library(packcircles)
    
    res <- circleLayout(xyr, limits, limits, maxiter = 1000)
    cat(res$niter, "iterations performed")
    
    library(ggplot2)
    library(gridExtra)
    dat.after <- circlePlotData(res$layout)
    
    doPlot <- function(dat, title)
      ggplot(dat) + 
      geom_polygon(aes(x, y, group=id), colour="brown", fill="burlywood", alpha=0.3) +
      coord_equal(xlim=limits, ylim=limits) +
      theme_bw() +
      theme(axis.text=element_blank(),
            axis.ticks=element_blank(),
            axis.title=element_blank()) +
      labs(title=title)
    
    grid.arrange(
    doPlot(dat.before, "before"),
      doPlot(dat.after, "after"),
      nrow=1)
    

    enter image description here

    You'll have to add geom_segment to get the bubbles to look like pies though I'm sure there's a better way than that using ggplot2