Search code examples
rggplot2plotpie-chart

Plotting multiple Pie Charts with label in one plot


I came across this question the other day and tried to re-create it for myself. ggplot, facet, piechart: placing text in the middle of pie chart slices . My data is in a very similar format, but sadly the accepted answer did not help, hence why I am re posting.

I essentially want to create the accepted answer but with my own data, yet the issue I run into is that coord_polar does not support free scale. Using the first answer: test_pie

I tried it using the second version of the answer, with the ddplyr version, but I also do not get my desired output. Using the second answer: test_pie2

Clearly none of these has the desired effect. I would prefer to create one as with size pie charts, but only showed four as an example, follows: desired_pie. This I did in excel, but with one legend, and no background grid.

Code

title<-c(1,1,2,2,3,3,4,4,5,5,6,6)
type<-c('A','B','A','B','A','B','A','B','A','B','A','B')
value<-c(0.25,0.75,0.3,0.7,0.4,0.6,0.5,0.5,0.1,0.9,0.15,0.85)

piec<-data.frame(title,type,value)
library(tidyverse)    

p1<-ggplot(data = piec, aes(x = "", y = value, fill = type)) + 
  geom_bar(stat = "identity") +
  geom_text(aes(label = value), position = position_stack(vjust = 0.5)) +
  coord_polar(theta = "y") 
  #facet_grid(title ~ ., scales = "free")
p1


piec <- piec %>% group_by(title) %>% mutate(pos=cumsum(value)-0.5*value)
p2<-ggplot(data = piec) + 
  geom_bar(aes(x = "", y = value, fill = type), stat = "identity") +
  geom_text(aes(x = "", y = pos, label = value)) +
  coord_polar(theta = "y") 
  #facet_grid(Channel ~ ., scales = "free") 
p2

Solution

  • You don't have to supply different y values for geom_text and geom_bar (use y = value for both of them). Next you have to specify position in geom_text. Finally, remove scales from facets.

    library(ggplot2)
    
    title<-c(1,1,2,2,3,3,4,4,5,5,6,6)
    type<-c('A','B','A','B','A','B','A','B','A','B','A','B')
    value<-c(0.25,0.75,0.3,0.7,0.4,0.6,0.5,0.5,0.1,0.9,0.15,0.85)
    piec<-data.frame(title,type,value)
    
    ggplot(piec, aes("", value, fill = type)) + 
        geom_bar(stat = "identity", color = "white", size = 1) +
        geom_text(aes(label = paste0(value * 100, "%")), 
                  position = position_stack(vjust = 0.5), 
                  color = "white", size = 3) +
        coord_polar(theta = "y") +
        facet_wrap(~ title, ncol = 3) +
        scale_fill_manual(values = c("#0048cc", "#cc8400")) +
        theme_void()
    

    enter image description here