Search code examples
rggplot2pie-chartr-plotly

How to combine multiple pie charts wih a loop using plotly or ggplot


I have the following dataframe (in a reduced version, it can achieve up to 1000 variables) and I'd like to build multiple pie charts for each of the columns of my dataframe. I found this code in order to build them with a loop using plotly (but suggestions with ggplot would be good, too) but I don't know how to plot them together, in a single plot, using a loop to combine them. The dataset is the following:

a=c(20.0,20.0,20.0,20.0,20.0)
b=c(19.0,21.0,22.0,18.0,20.0)
c=c(20.0,20.5,19.5,15.0,25.0)
d=c(13.0,17.0,15.5,24.5,20.0)
e=c(20.0,10.5,29.5,35.0,5.0)
data=cbind(a,b,c,d,e)
colnames(data)<-c("A","B","C","D","E")
rownames(data)<-c("A","B","C","D","E")
data=as.table(data)
data

while the code for writing the different pie charts is, as follows:

for(i in 1:dim(data)[1]){
  assign(paste0("pie_",i), plot_ly(as.data.frame(data[,i], nm = "y"), 
                                 labels = colnames(data), values = ~y, type = 'pie'))
}

I'd like to combine all the created pie charts together, using a loop in order to make the combination automatic according to the number of different columns (variables) in the dataframe. Thank you in advance for the help!


Solution

  • Here a ggplot2 solution, that avoids loops, as ggplot2::facet_wrap() does the job simply:

    library(reshape2)
    library(tidyverse)
    
    melt(data) %>%                                # ggplot loves long format
    ggplot(aes("", value, fill = Var1)) +         # here the variables
                   geom_bar(stat = 'identity') +  # bars
                   coord_polar("y") +             # make it round
                   facet_wrap(vars(Var2))         # facets
    

    enter image description here

    If I can advice you, generally bar charts to 100 are imho a bit better, because they make easier the comparisons between bars instead of circles (there lot of opinions about it). In case, the code is more simple, and you're allowed to use plotly, due supported (it seems coord_polar() is not supported yet).

    library(plotly)
    p <- melt(data) %>% ggplot(aes(Var2, value, fill = Var1)) +
                   geom_bar(stat = 'identity')
    
    ggplotly(p)
    

    enter image description here