And*_*usZ 23 r facet ggplot2 pie-chart
我想在分面饼图上添加数据标签.
也许有人可以帮助我.
我的数据:
year <- c(1,2,1,2,1,2)
prod <- c(1,1,2,2,3,3)
quantity <- c(33,50,33,25,34,25)
df <- data.frame(year, prod, quantity)
rm(year, prod, quantity)
Run Code Online (Sandbox Code Playgroud)
码:
library(ggplot2)
# center's calculated by hand
centr2 <- c(16, 25, 49, 62.5, 81, 87.5)
ggplot(data=df, aes(x=factor(1), y=quantity, fill=factor(prod))) +
geom_bar(stat="identity") +
geom_text(aes(x= factor(1), y=centr2, label = df$quantity), size=10) +
facet_grid(facets = .~year, labeller = label_value) +
coord_polar(theta = "y")
Run Code Online (Sandbox Code Playgroud)
我的结果是:

如果我删除coord_polar(theta ="y"),我将得到以下图:

现在我很清楚,为什么我的数据标签不匹配.
但我不知道如何解决它.
我读到:
1.在饼图上放置标签
2. 在带有刻面密度的ggplot中添加文本
3. 饼图将其文本放在彼此的顶部
但没有找到答案.
tal*_*lat 23
我会通过定义另一个变量(我调用pos)df来计算文本标签的位置.我这样做dplyr但你也可以使用其他方法.
library(dplyr)
library(ggplot2)
df <- df %>% group_by(year) %>% mutate(pos = cumsum(quantity)- quantity/2)
ggplot(data=df, aes(x=factor(1), y=quantity, fill=factor(prod))) +
geom_bar(stat="identity") +
geom_text(aes(x= factor(1), y=pos, label = quantity), size=10) + # note y = pos
facet_grid(facets = .~year, labeller = label_value) +
coord_polar(theta = "y")
Run Code Online (Sandbox Code Playgroud)
