Despite my better efforts as an R newcomer, I can't seem to figure out how to label the slices of a pie chart created with ggplot2.
I have a data.frame (tibble) that I need to filter by "Sample" and plot as separate pie charts. The data looks like this (including "lab.ypos" which I add in an effort to map my geom_text locations (see failed code):
# 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
I've managed to get an appropriate lookin chart without labels, but as soon as I try to calculate label positions for my filtered data sets, it all fails.
# 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)
The expectation is that I get a pie plot with each slice labeled with "Relative_Contribution" in the middle of the slice. What happens, however, is only a fraction of a pie chart that may or may not be labeled correctly.