将 % 标签添加到 ggplot2 多饼图

Adding % labels to ggplot2 multi-pie chart

我创建了一些不错的饼图,但在向饼图添加 % 标签时遇到困难。环境是 Linux.

输入数据是制表符分隔的文本文件:

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

我的代码:

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()

输出:

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

只需将 geom_text() 更改为:

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

这只会显示您的百分比大于 0% 的标签,因为这些情况在您的绘图中没有可见区域。