2

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)

enter image description here

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)

enter image description here

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?

4

1 回答 1

7

最好通过创建一个位置变量来达到预期的结果(正如我在这个答案中所展示的那样)。将此方法应用于您的情况:

# creating the position variable
library(dplyr)
df <- df %>%
  group_by(id) %>%
  mutate(pos=cumsum(value) - 0.5*value)

# creating the plot
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=pos, label=sprintf("%.1f", value)), size = 5, colour = "grey25") +
  facet_wrap( ~ id)

这使: 在此处输入图像描述

于 2014-06-23T13:15:54.880 回答