Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r-plotly: pie chart with values in stead of percentages

Tags:

r

plotly

I need to make a pie chart with R plotly, but in stead of showing the percentages, I would like the raw counts overlaid on the pie sections (i.e. 300, 250, 110, 190).

The code below makes the pie chart, but with percentages.

WhatIHave <- c("Money" = 300,
            "Dinosaurs" = 250,
            "Aether" = 110,
            "Discussions" = 190)
data <- data.frame("Category" = names(WhatIHave), WhatIHave)

p <- plot_ly(data, labels = ~Category, values = ~WhatIHave, type = 'pie') %>%
    layout(title = 'Lovely Pie',
           xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
           yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
p

I can't believe this hasn't been asked before, but I really could not find it in previous questions, or in the plotly documentation. Apologies if this turns out to be a duplicate question.

like image 935
Nibood_the_slightly_advanced Avatar asked Sep 05 '25 03:09

Nibood_the_slightly_advanced


1 Answers

You could create a character vector called vals to use in the piechart

vals <- paste(data$WhatIHave, sep = "")

p <- plot_ly(data, labels = ~Category, values = ~WhatIHave, type = 'pie', textinfo = "text", text = vals) %>%
    layout(title = 'Lovely Pie',
           xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
           yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
p

Edit

If you want to include both the values and the percentages, you can do:

textinfo = "text + values"
like image 186
Matt Avatar answered Sep 07 '25 23:09

Matt