I need to plot three pie charts using the following data frame:
df <- data.frame(id = rep(LETTERS[1:3], each=5),
var = rep(letters[1:5], 3),
value = c(10, 8, 6, 4, 2))
This code produce the type of chart I want:
library(ggplot2)
ggplot(df, aes(x = factor(1), fill = var, weight=value)) +
geom_bar(width = 1.2, colour = "white") +
coord_polar(theta="y") +
facet_wrap( ~ id)
The problem arise when I need to add some text to label each slice of the pie:
ggplot(df, aes(x = factor(1), fill = var, weight=value)) +
geom_bar(width = 1.2, colour = "white") +
coord_polar(theta="y") +
geom_text(aes(x = 1.8, y=rowMeans(embed(c(0,cumsum(value)),2)),
label=sprintf("%.1f", value)), size = 5, colour = "grey25") +
facet_wrap( ~ id)
It seems that rowMeans(embed(c(0,cumsum(value)),2))
is not evaluated against the portion of data being displayed by each facet (as I would expect).
Having created a very trivial case, the positions should be always the same:
> rowMeans(embed(c(0,cumsum(df$value[ df$id == "A"])),2))
[1] 5 14 21 26 29
> rowMeans(embed(c(0,cumsum(df$value[ df$id == "B"])),2))
[1] 5 14 21 26 29
> rowMeans(embed(c(0,cumsum(df$value[ df$id == "C"])),2))
[1] 5 14 21 26 29
Q: What is actually ggplot
doing when evaluating the above expression?