R代表另一个循环

时间:2017-04-19 09:39:11

标签: r for-loop plotly

我有一个数据,我是其中的一部分:

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

我使用for-loop,代码如下:

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))
}

Products 1中的结果只显示Year 2015 我知道我是否可以在其中使用另一个for循环?所以我可以得到每个产品和他们每年的饼图 谢谢。

1 个答案:

答案 0 :(得分:1)

您可以为每个产品和年份组合绘制值。

首先通过plot_ly定义一个空图,然后分别添加每个饼图并通过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
相关问题