尽管我作为R新手做出了更大的努力,但我似乎无法弄清楚如何标记由ggplot2创建的饼图的切片。
我有一个data.frame(小标题),我需要按“样本”进行过滤并将其绘制为单独的饼图。数据看起来像这样(包括“ lab.ypos”,我添加了它以映射我的geom_text位置(请参见失败的代码):
# A tibble: 30 x 4
Sample Source_Names Relative_Contribution lab.ypos
<chr> <chr> <dbl> <dbl>
1 FH3 CMB 81.4 40.7
2 FH3 SM 2.2 82.5
3 FH3 Uinta 16.4 91.8
4 SC1 CMB 72.4 36.2
5 SC1 SM 7 75.9
6 SC1 Uinta 20.5 89.6
7 5-SC CMB 68.6 34.3
8 5-SC SM 0.7 69.0
9 5-SC Uinta 30.8 84.7
10 PL3 CMB 1.6 0.8
我设法获得了一个没有标签的合适的查找表,但是一旦我尝试为过滤后的数据集计算标签位置,一切都会失败。
# round data to 1 decimal place and add label position
DZmix_all_edit <- DZmix_all %>%
mutate(Relative_Contribution=round(Relative_Contribution,1)) %>%
group_by(Sample) %>%
mutate(lab.ypos = cumsum(Relative_Contribution) - 0.5*Relative_Contribution)
# subset data
DZmix.FH3 <- filter(DZmix_all_edit, Sample == "FH3")
# define color scheme
# SM = "#cccccc", Uinta = "#969696", CMB = "#636363"
DZmix.colrs <- c("#636363", "#cccccc", "#969696")
# Black and White pie plots
ggplot(DZmix.FH3, aes(x = "", y = Source_Names, fill = factor(Source_Names))) +
geom_bar(width = 1, stat = "identity") +
theme_void() +
theme(axis.line = element_blank(),
plot.title = element_text(hjust=0.5)) +
scale_fill_manual(values = DZmix.colrs) +
geom_text(aes(y = lab.ypos, label = Relative_Contribution), color = "white")+
labs(fill="Potential Source",
x=NULL,
y=NULL,
title=NULL,
caption=NULL) +
coord_polar(theta = "y", start=0)
期望是我得到一个饼图,每个切片的中间都标有“ Relative_Contribution”。但是,发生的事情只是饼图中的一小部分,可能不会正确标注。