Search code examples
rggplot2pie-chartfacet

R - pie chart in facet


I have four pie charts which I need them all to be displayed in two lines and two columns. I use the below script to display the one:

slices <- c(39, 7, 13)
lbls <- c("monthly", "daily", "weekly")
pct <- slices
lbls <- paste(lbls, pct) 
pie(slices,labels = lbls, col=rainbow(length(lbls)),
    main="Purchased Products")

How can I create three more of them with different main titles each time if the other three pie charts values are as below:

slices <- c(40, 5, 12)
lbls <- c("monthly", "daily", "weekly")

slices <- c(15, 27, 47)
lbls <- c("monthly", "daily", "weekly")

slices <- c(58, 47, 2)
lbls <- c("monthly", "daily", "weekly")

Solution

  • Something like will work. You just have to change how your data is formatted and use ggplot2 which is in the tidyverse.

    library(tidyverse)
    
    df1 <- expand_grid(pie = 1:4, labels = c("monthly", "daily", "weekly"))
    df2 <- tibble(slices = c(39, 7, 13,
                             40, 5, 12,
                             15, 27, 47,
                             58, 47, 2))
    
    # join the data
    df <- bind_cols(df1, df2) %>% 
      group_by(pie) %>% 
      mutate(pct = slices/sum(slices)*100) # pct for the pie - adds to 100
      
    # graph
    ggplot(df, aes(x="", y=pct, fill=labels)) + # pct used here so slices add to 100
      geom_bar(stat="identity", width=1) +
      coord_polar("y", start=0) +
      geom_text(aes(label = slices), position = position_stack(vjust=0.5)) +
      facet_wrap(~pie, ncol = 2) +
      theme_void() +
      theme(legend.position = "bottom")
    

    enter image description here

    Using an edited version of your data

    > df
    # A tibble: 12 x 4
    # Groups:   pie [4]
         pie labels  slices   pct
       <int> <chr>    <dbl> <dbl>
     1     1 monthly     39    66
     2     1 daily        7    12
     3     1 weekly      13    22
     4     2 monthly     40    70
     5     2 daily        5     9
     6     2 weekly      12    21
     7     3 monthly     15    17
     8     3 daily       27    30
     9     3 weekly      47    53
    10     4 monthly     58    54
    11     4 daily       47    44
    12     4 weekly       2     2