我需要使用以下数据框绘制三个饼图:
df <- data.frame(id = rep(LETTERS[1:3], each=5),
var = rep(letters[1:5], 3),
value = c(10, 8, 6, 4, 2))
此代码生成我想要的图表类型:
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)
当我需要添加一些文本来标记饼图的每个切片时,会出现问题:
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)
似乎rowMeans(embed(c(0,cumsum(value)),2))
未针对每个方面显示的数据部分进行评估(正如我所料)。
创造了一个非常微不足道的案例,这些职位应始终保持不变:
> 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
问:在评估上述表达式时,ggplot
实际上做了什么?
答案 0 :(得分:7)
通过创建位置变量来实现所需的结果会更好(正如我在this answer中所示)。将此方法应用于您的情况:
# 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)
给出: