Mic*_*ele 2 r facet ggplot2 pie-chart geom-text
我需要使用以下数据框绘制三个饼图:
df <- data.frame(id = rep(LETTERS[1:3], each=5),
var = rep(letters[1:5], 3),
value = c(10, 8, 6, 4, 2))
Run Code Online (Sandbox Code Playgroud)
此代码生成我想要的图表类型:
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)
Run Code Online (Sandbox Code Playgroud)

当我需要添加一些文本来标记饼图的每个切片时,会出现问题:
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)
Run Code Online (Sandbox Code Playgroud)

似乎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
Run Code Online (Sandbox Code Playgroud)
问:ggplot评估上述表达式时实际上在做什么?
最好通过创建一个位置变量来实现所需的结果(正如我在本回答中所示).将此方法应用于您的情况:
# 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)
Run Code Online (Sandbox Code Playgroud)
这使:
