Search code examples
rdonut-chart

Placing two Pie Charts from lessR side by side in one figure


The lessR package can do some pretty nice things, and it makes donut plots simpler than any other package. How does one place two pie charts next to each other in a single plot? I know it can do a trellis for multi-panels, but in the example here that doesn't seem to be an option.


d <- data.frame(
  gender = c("M","M","M","M","M","F","M","M","M","M","M","M","F","M","M","M","F","M","M","M"),
  ethnic_grp = c("WHITE","ASIAN","ASIAN","MULTIETH","MULTIETH","BLACK","NSPEC","ASIAN","ASIAN", "WHITE", "HISPA", "NSPEC","MULTIETH","ASIAN","ASIAN","ASIAN","HISPA","ASIAN","BLACK","MULTIETH")
  )
#chart 1
PieChart(ethnic_grp, fill = "viridis",
         main = NULL, quiet=TRUE)
#chart 2
PieChart(gender, fill = "heat",
         main = NULL, quiet=TRUE)

Rather than produce them in sequence, I'd prefer something like: enter image description here

I have used ggplot2 to recreate this, but it requires far more work to create these plots that way.


Solution

  • You can do that easily with the add parameter in PieChart. It is pretty straightforward.

    First of all, you'll need to use the par function to define the grid i.e number of rows and columns you need based on the number of plots you have.

    In your case, you'll need par(mfrow = c(1, 2)) which will plot two plots adjacent to each other.

    The whole code looks like this:

    library(lessR)
    d <- data.frame(
      gender = c("M","M","M","M","M","F","M","M","M","M","M","M","F","M","M","M","F","M","M","M"),
      ethnic_grp = c("WHITE","ASIAN","ASIAN","MULTIETH","MULTIETH","BLACK","NSPEC","ASIAN","ASIAN", "WHITE", "HISPA", "NSPEC","MULTIETH","ASIAN","ASIAN","ASIAN","HISPA","ASIAN","BLACK","MULTIETH")
    )
    
    par(mfrow = c(1, 2))
    #chart 1
    PieChart(ethnic_grp, fill = "viridis",
             main = NULL, quiet=TRUE,  add = PieChart(gender, fill = "heat",
                                                      main = NULL, quiet=TRUE)) 
    

    Notice, that instead of plotting two charts separately, you'll need to add the other plots inside the add parameter of the first chart.

    The output looks like this:

    enter image description here