Search code examples
rpie-chart

R multiple pie charts from count table?


If my data looks like this:

group <- c("A","B","C","D")
count1 <- c(1:4)
count2 <- c(2,2,3,4)
count3 <- c(4,3,2,1)
data <- cbind(group,count1,count2,count3)

how can I get pie charts of rows and of columns? That is, a single plot with 4 pie charts and one legend for the distribution of count variables within groups, and a plot with 3 pie charts for the distribution of groups within each count? Also, if theres a better way then pie charts to show this, I'd be happy for offers.


Solution

  • Fix example data, so it's numeric and not character (using rbind forces to matrix. A matrix can only hold a single data type, and R always uses the most general one in these cases, i.e. character):

    group<-c("A","B","C","D")
    count1<-c(1:4)
    count2<-c(2,2,3,4)
    count3<-c(4,3,2,1)
    df <- data.frame(group,count1,count2,count3)
    

    Suggested solution using ggplot2 for plottig as well as dplyr and tidyr for restructuring data into long form:

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    
    df %>% 
      pivot_longer(cols=-group) %>% 
      ggplot(aes(group, value, fill=name)) +
      geom_col(position = "dodge")
    

    enter image description here

    Alternativey we could use facet_grid or facet_wrap...

    Edit:

    How to show relative percentages per group (using ggplot2, tidyr, dplyr and scales):

    group<-c("A","B","C","D")
    count1<-c(1:4)
    count2<-c(2,2,3,4)
    count3<-c(4,3,2,1)
    df <- data.frame(group, count1, count2, count3)
    
    
    library(dplyr)
    library(tidyr)
    library(ggplot2)
    library(scales)
    
    df %>% 
      pivot_longer(cols=-group) %>% 
      group_by(group) %>% 
      mutate(relFreq = value / sum(value)) %>% 
      ungroup() %>% 
      ggplot(aes(group, relFreq, fill=name)) +
      geom_col(position = "dodge") +
      scale_y_continuous(labels = scales::percent) +
      expand_limits(y=c(0,1))
    

    enter image description here