向ggplot2多层图表添加%标签

时间:2018-11-21 03:26:19

标签: r ggplot2 label 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()

输出:

Multi-Pie

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

1 个答案:

答案 0 :(得分:2)

只需将geom_text()更改为:

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

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