Peter Chen
Peter Chen

Reputation: 1484

R for loop in another one

I have a data and I subset part of it:

Products      degrees     Year      Value  
1               A         2015      2234751
1               A         2016      1583064
1               A         2017       331248
1               B         2015    174022286
1               B         2016    192980994
1               B         2017     32368003  
2               A         2016     31546895
2               A         2017     56789215
2               B         2016       598752
2               B         2017    145687895

And I use for-loop and the code is in the following:

for(i in unique(data$Products)){
plot_ly(data[data$Products == i,], labels = ~degrees, values = ~value, type = 'pie',
               textposition = 'inside',
               textinfo = 'label+percent',
               insidetextfont = list(color = '#FFFFFF'),
               hoverinfo = 'text') %>%
     layout(title = '',
            xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
            yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
}

The result in Products 1 just show Year 2015.
I have an idea whether I can use another for-loop in this? So I can get each products and their each year's pie chart.
Thank You.

Upvotes: 1

Views: 118

Answers (1)

Maximilian Peters
Maximilian Peters

Reputation: 31679

You could plot for each product and year combination the values.

You first define an empty plot via plot_ly and then add each pie chart separately and specify its position via domain.

enter image description here

data = data.frame(Products=c(1,1,1,1,1,1,2,2,2,2), 
 degrees= c("A","A","A","B","B","B","A","A","B","B"),
 year=c(2015,2016,2017,2015,2016,2017,2016,2017,2016,2017),
 value=c(2234751, 1583064, 331248, 174022286, 192980994, 32368003, 31546895, 56789215, 598752, 145687895))


p <- plot_ly()
counter <- 0
total <- nrow(unique(expand.grid(data$Products, data$year)))

for(product in unique(data$Products)) {
  for(year in unique(data[data$Products == product,]$year)) {
    print(product)
    print(year)
    p <- add_pie(p, 
               data=data[(data$Products == product) & (data$year == year),], 
               values = ~value, 
               labels = ~degrees,
               type = 'pie',
               name = paste(product, year),
               domain = list(x = c(counter / total, (counter + 1) / total),
                             y = c(0,1))
    )
    counter <- counter + 1

  }
}

p <- layout(p, 
            title = '',
            xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
            yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
p

Upvotes: 2

Related Questions