How to adjust labels on a pie chart in ggplot2

Hi All!
I would like to either put a count associated with each section of the pie chart or put a percentage that each slice makes up of the pie.
Thanks

pie_chart_df_ex <- data.frame("Category" = c("Baseball", "Basketball", "Football", "Hockey"), "freq" = c(510, 66, 49, 21))
pie_chart <- ggplot(pie_chart_df_ex, aes (x="", y = freq, fill = factor(category))) + 
    geom_bar(width = 1, stat = "identity") + 
    theme(axis.line = element_blank(),
          plot.title = element_text(hjust=0.5)) + 
    labs(fill = "category",
         x = NULL,
         y = NULL,
         title = "Pie Chart of Blue Chip Makeup")
#> Error in ggplot(pie_chart_df, aes(x = "", y = freq, fill = factor(category))): could not find function "ggplot"
pie_chart + coord_polar("y")
#> Error in eval(expr, envir, enclos): object 'pie_chart' not found

Created on 2019-08-23 by the reprex package (v0.3.0)

Like this?

library(ggplot2)

pie_chart_df_ex <- data.frame(Category = c("Baseball", "Basketball", "Football", "Hockey"), "freq" = c(510, 66, 49, 21))

ggplot(pie_chart_df_ex, aes (x="", y = freq, fill = factor(Category))) + 
  geom_bar(width = 1, stat = "identity") +
  geom_text(aes(label = paste(round(freq / sum(freq) * 100, 1), "%")),
            position = position_stack(vjust = 0.5)) +
  theme_classic() +
  theme(plot.title = element_text(hjust=0.5),
        axis.line = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank()) +
  labs(fill = "Category",
       x = NULL,
       y = NULL,
       title = "Pie Chart of Blue Chip Makeup") + 
  coord_polar("y")

2 Likes

Thank you!
Yea that's good I just don't like how one of the percentage marks is covering another. Is there an easy way to alter that?

It is a little tricky but you can play with the numbers to fine tune to your liking

library(ggplot2)

pie_chart_df_ex <- data.frame(Category = c("Baseball", "Basketball", "Football", "Hockey"), "freq" = c(510, 66, 49, 21))

ggplot(pie_chart_df_ex, aes (x="", y = freq, fill = factor(Category))) + 
  geom_col(position = 'stack', width = 1) +
  geom_text(aes(label = paste(round(freq / sum(freq) * 100, 1), "%"), x = 1.3),
            position = position_stack(vjust = 0.5)) +
  theme_classic() +
  theme(plot.title = element_text(hjust=0.5),
        axis.line = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank()) +
  labs(fill = "Category",
       x = NULL,
       y = NULL,
       title = "Pie Chart of Blue Chip Makeup") + 
  coord_polar("y")

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.