Search code examples
rggplot2geom-barfacet-wrap

Multiple pies facet_wrap in columns and rows in ggplot


I would like to have a plot with three main columns (Variable Letter_ph), and 4 rows (Variable_tr), with full pies which are filled by the values from Type_tx.

Such as this enter image description here

But I have this, can I please have some help? Thank you

data <- tibble::tibble(
          value = c(18.3,47.2,53.5,8.6,61.4,114.24,43.7,0,82.7,9.017,18.49,35.79,3.76,25.2,56.5,21.3,0,42.36,18.14,0,47.69,2.4,3.1,10.0,1.18,4.1,9.1,3.1,5.0,21.2,1.5,6.6,18.6,6.4,0,12.5),
  Letter_ph = c("I", "M", "F","I", "M", "F","I", "M", "F","I", "M", "F","I", "M", "F","I", "M", "F","I", "M", "F","I", "M", "F","I", "M", "F","I", "M", "F","I", "M", "F","I", "M", "F"),
      Variable_tr = rep(c(rep("A",3),rep("B",3),rep("C",3),rep("A",3),rep("B",3),rep("C",3),rep("A",3),rep("B",3),rep("C",3),rep("A",3),rep("B",3),rep("C",3))),
        Type_tx = rep(c(rep("T1",9),rep("T2",9),rep("T3",9), rep("T4", 9))))
        


ggplot( data, aes( x = "", y = Variable_tr, fill=Type_tx ) ) + 
      geom_bar( stat = "identity" ) + 
      facet_wrap( ~ Variable_tr, ncol=4 ) + 
   theme_classic()+
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid  = element_blank())+ 
  coord_polar(theta='y', start = pi / 3)+
      xlab("Letter ph (IMF)")

enter image description here


Solution

  • As well as changing the dependent variable to "value" and correcting the facet_wrap() statement, if you want full pies (Who doesn't?) then they have to sum up to the same value.

    Do this by pivoting the data wider, dividing each of T1:T4 by the sum of the row and then pivoting long again to plot.

    data %>% 
      pivot_wider(names_from = Type_tx, values_from = value) %>% 
      rowwise() %>% 
      mutate(across(T1:T4, ~ ./sum(T1, T2, T3, T4))*100) %>% 
      pivot_longer(-c(Letter_ph, Variable_tr), names_to = "Type_tx") %>% 
    
      ggplot(aes( x = "", y = value, fill=Type_tx ) ) + 
      geom_bar(stat = "identity" ) + 
      facet_wrap(Letter_ph ~ Variable_tr) + 
      theme_classic()+
      theme(axis.text = element_blank(),
            axis.ticks = element_blank(),
            panel.grid  = element_blank())+ 
      coord_polar(theta='y', start = pi / 3)+
      xlab("Letter ph (IMF)")
    

    enter image description here