Steve
Steve

Reputation: 175

Rounding off percentages in plotly pie charts

label=c("<25%","25 - 50%",">75%")
values=c(4,2,3)
df=data.frame(label,values)
plot_ly(df, labels = ~label, values = ~values,text=values,textposition="auto", type = 'pie') %>%layout(title = 'Percentage Effort time',showlegend=T,
     xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
     yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

When I run this code, I get a pie chart with percentages and the numbers. How can I obtain percentages that are rounded off to whole numbers instead of decimal points?

Pie chart

Upvotes: 5

Views: 8493

Answers (4)

mailo
mailo

Reputation: 37

within the brackets of plot_ly(), add:

texttemplate='%{percent:.2p}'

Upvotes: 1

Huiyan Wan
Huiyan Wan

Reputation: 2099

This would give you 2 digits rounded percentage, with value shown multiply by 100 and suffix with "%":

texttemplate = '%{text:.2p}'

Here is the complete reference of d3-format's syntax I found in the documentation.

Upvotes: 1

LianeH
LianeH

Reputation: 11

A newer method for if you'd like to avoid creating a text template to 'overwrite' the values shown in the default way (works in python):

fig.update_traces(
        textposition="outside",
        texttemplate="%{label} (%{percent:.1%f})",
        ... 

Th2 ':.1%f' portion will round values to 1 decimal place, while ':.0%f' will give values rounded to whole numbers

Upvotes: 1

Frank Schmitt
Frank Schmitt

Reputation: 30775

You can use textinfo='text' to hide the percent values and provide a custom formatted label with text:

    text = ~paste(round((values / sum(values))*100, 0)),
    textinfo='text',

Complete example:

library(magrittr)
library(plotly)

label=c("<25%","25 - 50%",">75%")
values=c(4,2,3)
df=data.frame(label,values)
plot_ly(df, 
        labels = ~label, 
        values = ~values,
        text = ~paste(round((values / sum(values))*100, 0)),
        #textinfo='none',
        #textinfo='label+value+percent',
        textinfo='text',
        textposition="auto", type = 'pie') %>% layout(title = 'Percentage Effort time', showlegend=T,
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)
        )

Upvotes: 5

Related Questions