Search code examples
rpie-chartplotlydata-manipulation

R draw 2 pie charts with plotly


I have a question about drawing pie charts.
Following is my csv raw data:

type,com,year,month,value
type,com,year,month,value
A,CH,2015,1,0
A,CH,2015,2,0
A,CH,2015,3,0
A,CH,2015,4,0
A,CH,2015,5,0
A,CH,2015,6,0
A,CH,2015,7,0
A,CH,2015,8,2200
A,CH,2015,9,111384
A,CH,2015,10,28758
A,CH,2015,11,21161
A,CH,2015,12,0
A,CH,2016,1,0
A,CH,2016,2,0
A,CH,2016,3,0
A,CH,2016,4,0
A,CH,2016,5,0
A,CH,2016,6,0
A,CH,2016,7,0
A,CH,2016,8,0
A,CH,2016,9,453128
A,CH,2016,10,868256
A,CH,2016,11,1015080
A,CH,2016,12,650912
A,ZU,2015,1,0
A,ZU,2015,2,0
A,ZU,2015,3,0
A,ZU,2015,4,0
A,ZU,2015,5,0
A,ZU,2015,6,61273
A,ZU,2015,7,27711
A,ZU,2015,8,161780
A,ZU,2015,9,48889
A,ZU,2015,10,72805
A,ZU,2015,11,131466
A,ZU,2015,12,73756
A,ZU,2016,1,400
A,ZU,2016,2,0
A,ZU,2016,3,0
A,ZU,2016,4,0
A,ZU,2016,5,0
A,ZU,2016,6,0
A,ZU,2016,7,0
A,ZU,2016,8,10000
A,ZU,2016,9,147533
A,ZU,2016,10,64572
A,ZU,2016,11,57542
A,ZU,2016,12,0

I use group_by() to group com & year.

by_comyear <- group_by(data, com, year)
sumdataA <- summarise(by_comyear, sum(value))
sumdataA
     com  year `sum(value)`
  <fctr> <int>        <int>
1     CH  2015       163503
2     CH  2016      2987376
3     ZU  2015       577680
4     ZU  2016       280047

However, I want to draw 2 pie charts. One for year 2015, another for year 2016.
How can I draw with package plotly: plot_ly() function
maybe I should separate sumdataA to 2?

very appreciate.


Solution

  • Not very clear what specifically you want to plot in the pie chart. This is just a basic example with year side by side. You could use:

    library(ggplot2)
    library(plotly)
    df <- data.frame(COM = c("ch", "ch", "zu","zu"), year = c("2015", "2016","2015", "2016"), values= c(100,125,65,17))
    data2015 <- filter(df, year == "2015")
    data2016 <- filter(df, year == "2016")
    
    plot_ly(data2015, labels = ~COM, values = ~ values, type = "pie", domain = list(x = c(0, 0.5), y = c(0, 1))) %>%
      add_trace(data = data2016, labels = ~COM, values = ~ values, type = "pie", domain = list(x = c(0.5, 1), y = c(0, 1)))
    

    Result: enter image description here