Search code examples
rtextpie-chartfacet-wrap

R: Trying to move the title of a facet-wrap to the front


Sorry if this has been asked before, tried looking around and couldn't find anything. I have the following code which produces 5 pie charts, side by side, with their respective titles at the top, and the n value at the bottom. :

Testing <- data.frame(
  Letter = c("A", "B", "C", "q", "g"),
  Category = c("Category A", "Category B",
               "Category A", "Category B",
               "Category A", "Category B",
               "Category A", "Category B",
               "Category A", "Category B"),
  Count = c(58, 16, 20, 42, 37,
            42, 84, 80, 58, 63),
  RawN = c("n = 100", "n = 200", "n = 300", "n = 400", "n = 500", 
           "n = 100", "n = 200", "n = 300", "n = 400", "n = 500")
)


ggplot(Testing, aes(x = "", y = Count, fill = factor(Category))) + 
  geom_col(width = 1, position = "stack") +
  facet_wrap( ~ Letter, ncol=5)+
  theme_void()+
  theme(legend.position = "bottom")+
  scale_fill_manual(labels = c("Category A", "Category B"),
                    values = c("blue", "red"))+
  labs(fill = "")+
  coord_polar(theta = "y")+
  geom_text(aes(label = RawN), 
            x = -Inf, y = Inf, hjust = 0.5, vjust = 7.9)

However, the titles for the letters "q" and "g" are cut off. I've tried playing with strip text and I couldn't get the letters to show properly. Is there a way to move the layers of the titles to the front so "q" and "g" aren't cut off by the pie-chart?

**Edited to fix data.frame that got cut off and tried adding output image

PieChartOutput


Solution

  • You could add theme(strip.text.x=element_text(margin=margin(b=5))), it will adjust the margin of your plot so that the labels are not covered :

    ggplot(Testing, aes(x = "", y = Count, fill = factor(Category))) + 
      geom_col(width = 1, position = "stack") +
      facet_wrap( ~ Letter, ncol=5)+
      theme_void()+
      theme(legend.position = "bottom")+
      scale_fill_manual(labels = c("Category A", "Category B"),
                        values = c("blue", "red"))+
      labs(fill = "")+
      coord_polar(theta = "y")+
      geom_text(aes(label = RawN), 
                x = -Inf, y = Inf, hjust = 0.5, vjust = 7.9)+
      theme(strip.text.x=element_text(margin=margin(b=1)))
    

    enter image description here