Search code examples
rggplot2pie-chartfacet-wrapgeom-text

How to enhance faceted pie charts labels in R?


I have an energy dataframe for the share of different sources of energy for several years:

Year<-c("2016","2016","2016","2017","2017","2017","2018","2018","2018")
Source<-c("coal","hydro","solar","coal","hydro","solar","coal","hydro","solar")
Share<-c(0.5,0.25,0.25,0.4,0.15,0.45,0.7,0.1,0.2)
df<-cbind.data.frame(Year,Source,Share)

I am trying to plot the dataframe as faceted pie charts for the several years:


ggplot(df, aes(x=1, y=Share, fill=Source)) +
  geom_bar(stat="identity", width=1,position="fill")+
  coord_polar("y", start=0) +
  geom_text(aes(label = paste0(round(Share*100), "%")),size=2)+
  labs(x = NULL, y = NULL, fill = NULL, title = "Energy Mix")+
  theme_classic() + theme(axis.line = element_blank(),
          axis.text = element_blank(),
          axis.ticks = element_blank(),
          plot.title = element_text(hjust = 0.5, color = "#666666"))+
  facet_wrap(~Year)

and I get the following result: enter image description here

How can I put the labels outside of the pie slices and centered for their arches, and how can I also add black thin borders to the slices? I know pie charts are not readable, and that bar charts are a bit better, but I am trying to play a bit diverse in options.

Many thanks in advance


Solution

  • Pie charts are basically stacked bar charts - thus you can apply the same rules. Comments in the code.

    library(ggplot2)
    Year<-c("2016","2016","2016","2017","2017","2017","2018","2018","2018")
    Source<-c("coal","hydro","solar","coal","hydro","solar","coal","hydro","solar")
    Share<-c(0.5,0.25,0.25,0.4,0.15,0.45,0.7,0.1,0.2)
    
    ## don't do that cbind stuff
    df<-data.frame(Year,Source,Share)
    
    ggplot(df, aes(x=1, y=Share, fill=Source)) +
      ## geom_col is geom_bar(stat = "identity")(bit shorter)
      ## use color = black for the outline
      geom_col(width=1,position="fill", color = "black")+
      coord_polar("y", start=0) +
      ## the "radial" position is defined by x = play around with the values
      ## the position along the circumference is defined by y, akin to 
      ## centering labels in stacked bar charts - you can center the
      ## label with the position argument
      geom_text(aes(x = 1.7, label = paste0(round(Share*100), "%")), size=2, 
                position = position_stack(vjust = 0.5))+
      labs(x = NULL, y = NULL, fill = NULL, title = "Energy Mix")+
      theme_classic() + theme(axis.line = element_blank(),
                              axis.text = element_blank(),
                              axis.ticks = element_blank(),
                              plot.title = element_text(hjust = 0.5, color = "#666666"))+
      facet_wrap(~Year)
    

    Created on 2021-12-19 by the reprex package (v2.0.1)