SepiaHippo
SepiaHippo

Reputation: 11

How to make a functioning pie chart, R

I am trying to make a pie chart in R that displays the percent of each section as a label. I was following this tutorial, (https://www.geeksforgeeks.org/r-pie-charts/). I modified it a little bit to make it similar to the data frame I am actually working with. When I try and run my code I get the error, "Error in edges * dx[i] : non-numeric argument to binary operator". It seems the error is coming from legend(), when I comment it out I get no error. Where am I going wrong?

Thanks in advance for any help.

df <- data.frame( geeks = c(23, 56, 20, 63),
                  labels = c("Mumbai", "Pune", "Chennai", "Bangalore"))

df <- mutate(df, percent = round(df$geeks/sum(df$geeks)*100, 1))

df_pie <- pie(df$geeks, 
              round(df$percent,1),
              main = "City pie chart",
              col = rainbow(length(df$geeks)),
              legend("topright", c(df$labels),
                     cex = 0.5, fill = rainbow(length(df$geeks))))

Upvotes: 0

Views: 2720

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174576

legend is a stand-alone function, not an argument to pie

pie(df$geeks, 
    round(df$percent,1),
    main = "City pie chart",
    col = rainbow(length(df$geeks)))

legend("topright", c(df$labels), fill = rainbow(length(df$geeks)))

enter image description here

You might get a nicer look with ggplot though:

library(ggplot)

ggplot(df, aes(x = 1, y = percent, fill = labels)) +
  geom_col() +
  coord_polar(theta = "y") +
  geom_text(aes(label = paste(percent, "%")),
            position = position_stack(vjust = 0.5),
            size = 8) +
  theme_void(base_size = 20) +
  scale_fill_brewer(name = NULL, palette = "Pastel2")

enter image description here

Upvotes: 2

Related Questions