user1607
user1607

Reputation: 551

ggplot - use pie chart to visualize number of items in each group in terms of percentages - R

I want to create two pie chart to show number of people in each level of the factor variable. However, I want to obtain two pie charts, one for two groups.

Here is an example:

library(ggplot2)
library(dplyr)

df <- filter(diamonds, color %in% c("E", "D"))

ggplot(df,aes(x= "", fill=cut)) + 
  geom_bar()+
  facet_wrap(~color)+
  ggtitle(" ") +
  coord_polar("y", start=0)

enter image description here

How can I Express the count of items per each group (cut) per each facet (color) as percentage? So on the end I would obtain two full pie charts with the precentages written inside the pie chart.

Upvotes: 1

Views: 3062

Answers (1)

Mikey Harper
Mikey Harper

Reputation: 15379

It is probably easiest to transform the data before you plot the graph. If we want to find the percentage of values within each group, we could use this answer:

df <- df %>%
  group_by(color, cut) %>%
  summarise(count = n()) %>%
  group_by(color) %>%
  mutate(per=count/sum(count)) %>% 
  ungroup()

df
# A tibble: 10 x 4
   color cut       count    per
   <ord> <ord>     <int>  <dbl>
 1 D     Fair        163 0.0241
 2 D     Good        662 0.0977
 3 D     Very Good  1513 0.223 
 4 D     Premium    1603 0.237 
 5 D     Ideal      2834 0.418 
 6 E     Fair        224 0.0229
 7 E     Good        933 0.0952
 8 E     Very Good  2400 0.245 
 9 E     Premium    2337 0.239 
10 E     Ideal      3903 0.398 

We can change the labels of the ggplot to percentage as below:

ggplot(df, aes(x= "", y = per, fill=cut)) + 
  geom_col() +
  facet_wrap(~color)+
  ggtitle(" ") +
  coord_polar("y", start=0) +
  scale_y_continuous(labels = scales::percent)

enter image description here

Upvotes: 1

Related Questions