Search code examples
rlabelpie-chart

Text and percentages in labels of pie chart


Hi I'm doing a basic pie chart, but when I do it only the "names" appear as the labels. I want the labels to be the names+percentage.

so I have:

reasons=prop.table(table(data$Reason[data$Stops %in% 1]))*100

with this I get:

DP 64
UV 20
TC 16

then

pie(reasons, color=rainbow(reasons), main="Distribution of Reasons")

With that I only get the pie with the labels DP, UV and TC.

What should I add to get DP 64%, UV 20%, TC 16% in the labels?


Solution

  • We can use the labels argument in pie

    library(dplyr)
    df <- read.table(text =
        "DP 64
    UV 20
    TC 16") %>%
        setNames(c("Reason", "Value")) %>%
        mutate(Percentage = sprintf("%s %3.1f%%", Reason, Value / sum(Value) * 100))
    with(df, pie(
        Value,
        labels = Percentage,
        col = rainbow(length(Value)),
        main = "Distribution of Reasons"))
    

    enter image description here