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

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. RStudio community helped me with this code in order to build them with a loop using plotly (but suggestions with ggplot2 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)){
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!

Using `ggplot2` you can do something like this (obviously you would have to style it a little bit more)

``````library(tidyverse)

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.data.frame() %>%
rownames_to_column() %>%
gather(column, value, -rowname) %>%
arrange(column) %>%
ggplot(aes(x = "", y = value, fill = rowname)) +
geom_col() +
coord_polar("y", start = 0) +
facet_wrap(~column)
`````` ``````
# column 'd' doesn't sum up 100
sum(d)
#>  90
``````

Created on 2019-08-23 by the reprex package (v0.3.0.9000)

1 Like

This question is also asked here:

Please familiarise yourself with the existing this post:

1 Like

Thanks a lot for the indication and sorry for that bother!

Thank you so much, the result is actually what I was looking for!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.