Search code examples
rplotnew-operatorpie-chart

Pie chart with multiple dummy variables


Lets suppose there are 4 persons and 3 groups (A, B, C) and 1 means it belongs to group X and 0 in other case. Lets suppose we have a database like this:

# A  B  C
1 0  0  1
2 0  1  0
3 1  0  0
4 1  0  0

What im trying to do is a pie chart that contains everygroup.

The code that im trying is

ggplot(data, aes(x="", y=data$A)) +
  geom_bar(stat="identity", width=1) +
  coord_polar("y", start=0)

However it only plots the pie chart of one variable. Thank you


Solution

  • I think this code performs the plot you want. I did some recoding using pivot_longer before making the plot.

    library(tidyverse)
    df %>%
      pivot_longer(cols = c(A,B,C),
                   names_to = "group",
                   values_to = "people") %>%
      group_by(group) %>%
      summarize(Sumppl = sum(people)) %>%
      ggplot(aes(x="", y = Sumppl, fill = group)) +
      geom_bar(stat = "identity",width = 1, position = "stack")+
      coord_polar("y") + 
      theme_minimal()+
      theme(axis.text.x=element_blank())
    

    Pie plot