1
votes

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.

1
Can you provide your dataset so that your example is reproducible? Also does this solve your question? stackoverflow.com/questions/27433798/…Michael Harper
@MichaelHarper I have added some datauser1607
Thanks for the data. it still wasn't truly reproducible as the head wasn't enough to reproduce the plot and the code contained lots of additional detail. I have updated your question to show how you could make it easier for others to help by 1) using a built in dataset (diamonds) and 2) removing additional code not related to the problem. Hope the example helpsMichael Harper

1 Answers

1
votes

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