Search code examples
rggplot2labelpie-chart

Adding % labels to ggplot2 multi-pie chart


I have created some nice pie charts but am having difficulty adding % labels to the pie charts. Environment is Linux.

Input data is a tab delimited text file:

TIMEFRAME   POPULATION  AMOUNT
Deepest_Ancestral   African 0.06
Deepest_Ancestral   East_Asian  0.23
Deepest_Ancestral   European    0.71
Deeper_Ancestral    African 0.00
Deeper_Ancestral    East_Asian  0.40
Deeper_Ancestral    European    0.60
Ancestral   African 0.00
Ancestral   East_Asian  0.10
Ancestral   European    0.90

MY CODE:

library(ggplot2)
library(dplyr)

file_name <- "X3.txt"

#load file into data frame
test <- read.csv(file_name, sep="\t", header = TRUE)

ggsave("MultiPie.png")


ggplot(test, aes(x="", y=AMOUNT, group=POPULATION, color=POPULATION, fill=POPULATION)) +
  geom_bar(width = 1, size = 0.5, color = "white", stat = "identity") +
  geom_text(aes(label = AMOUNT), position = position_stack(vjust = 0.5)) +
  coord_polar(theta = "y") + 
  facet_wrap(~ TIMEFRAME, nrow = 2, ncol = 2) + 
  ggtitle("MUTATIONS YOU SHARE WITH VARIOUS POPULATIONS\n\n") +
  theme(plot.title = element_text(family = "Arial", color="black", face="bold", size=12, hjust=0.5)) +
  theme(legend.title = element_text(family = "Arial", color="black", face="bold", size=10, hjust=0)) +
  scale_fill_manual(values = c("red4", "gold1", "blue2")) +
  scale_color_manual(values = c("red4", "gold1", "blue2")) +
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_blank(),
        panel.grid  = element_blank(), 
        legend.background = element_rect(fill = "gray80"),
        plot.background = element_rect(fill = "gray70"),
        panel.background = element_rect(fill = "grey70"), 
        legend.position = "bottom", legend.justification = "center")

dev.off()

THE OUTPUT:

Multi-Pie

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


Solution

  • Just change geom_text() to:

    geom_text(aes(label = ifelse(AMOUNT == 0, "", paste0(100*AMOUNT, "%"))),
              position = position_stack(vjust = 0.5))
    

    This will only display labels where your percents are larger than 0%, since those cases don't have a visible area in your plot.