R + ggplot2 =>添加标签在facet饼图[重复]

时间:2022-12-03 17:51:52

This question already has an answer here:

这个问题在这里已有答案:

I want to add data labels on faceted pie char.
Maybe someone can can help me.

我想在分面饼图上添加数据标签。也许有人可以帮助我。

My data:

我的数据:

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)

Code:

码:

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")

And my result is:

我的结果是:

R + ggplot2 =>添加标签在facet饼图[重复]

If I remove coord_polar(theta = "y"), I will have the following plot:

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

R + ggplot2 =>添加标签在facet饼图[重复]

And now it is clear for me, why my data labels did not match.
But I don't know how to fix it.

现在我很清楚,为什么我的数据标签不匹配。但我不知道如何解决它。

I read:
1. Place labels on Pie Chart
2. Add text to ggplot with facetted densities
3. Pie plot getting its text on top of each other

我读到:1。在饼图上放置标签2.在带有刻面密度的ggplot中添加文本3.饼图将其文本放在彼此的顶部

But didn't find the answer.

但没有找到答案。

1 个解决方案

#1


21  

I would approach this by defining another variable (which I call pos) in df that calculates the position of text labels. I do this with dplyr but you could also use other methods of course.

我会通过在df中定义另一个变量(我称之为pos)来计算文本标签的位置。我用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")

R + ggplot2 =>添加标签在facet饼图[重复]

#1


21  

I would approach this by defining another variable (which I call pos) in df that calculates the position of text labels. I do this with dplyr but you could also use other methods of course.

我会通过在df中定义另一个变量(我称之为pos)来计算文本标签的位置。我用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")

R + ggplot2 =>添加标签在facet饼图[重复]