Home > Back-end >  show total /sum of values in donut plot in R plotly
show total /sum of values in donut plot in R plotly

Time:02-18

I have a sample data set and I am trying to plot a basic donut plot in R via plotly. The code almost (currently the code below does not update the second color) works fine. Now, I want to show sum of the values of both the IDs under Type next to the respective percentages.

How can I do this?

Data

Value = c(50124,  9994,  9822, 13580,  5906,  7414, 16847,    59, 80550,  6824,  3111, 16756,  7702, 23034, 38058,  6729,  6951,     2,   408,
 37360, 20517, 18714,   352,     3, 42922, 30850,    21,  4667, 12220,  8762,   445,  1875,   719,   188,    26,   124,   996,    10,
    27,   304,    55, 34980,    67,     3,    25,  1012,  3588,    77,   847,    47,  1057,   924,   233,    40,     2,  2362,     3,
  1866,    16,     0,     0,     0)

Type = c("A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
"A", "A", "A", "A", "A", "A", "A", "A", "A", "A",  "A", 
"B",  "B",  "B",  "B",  "B",  "B",  "B",  "B",  "B",  "B",  "B", 
"B",  "B",  "B",  "B",  "B" "B", "B",  "B",  "B",  "B",  "B", 
"B",  "B",  "B",  "B",  "B",  "B",  "B")

df = data.frame(Type, Value) 

Code

    library(tidyverse)
    library(plotly)
    
    color = c('rgb(0,255,255)', 'rgb(255,127,80)')
    
    fig = df %>% plot_ly(labels = ~Type, 
                            values = ~Value,
                            #colors = c("grey50", "blue"),
                            marker = list(colors = color))
    fig = fig %>% add_pie(hole = 0.6,
                          text = ~paste(sum(Value)),
                          textinfo = "text   percent"))
    fig = fig %>% layout(title = "Title",  showlegend = T,
                          xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = T),
                          yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = T))
    
    fig

Desired output

enter image description here

CodePudding user response:

In your dataframe calculate a sum column and paste it in text = ~paste(sum)

df1 <- df %>% 
  group_by(Type) %>% 
  mutate(sum = sum(Value))


library(tidyverse)
library(plotly)

color = c('rgb(0,255,255)', 'rgb(255,127,80)')

fig = df1 %>% plot_ly(labels = ~Type, 
                     values = ~Value,
                     #colors = c("grey50", "blue"),
                     marker = list(colors = color))
fig = fig %>% add_pie(hole = 0.6,
                      text = ~paste(sum),
                      textinfo = "text   percent")
fig = fig %>% layout(title = "Title",  showlegend = T,
                     xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = T),
                     yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = T))

fig

enter image description here

  • Related