R + ggplot2 =>在构面饼图上添加标签 [英] R + ggplot2 => add labels on facet pie chart

查看:35
本文介绍了R + ggplot2 =>在构面饼图上添加标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的数据:

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)

代码:

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

我的结果是:

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

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

现在我很清楚为什么我的数据标签不匹配.
但我不知道如何修复它.

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

我读过:
1. 在饼图上放置标签
2. 将文本添加到具有分面密度的 ggplot
3. 饼图将其文本置于彼此之上

但是没有找到答案.

推荐答案

我会通过在 df 中定义另一个变量(我称之为 pos)来计算文本标签的位置.我用 dplyr 做到这一点,但你当然也可以使用其他方法.

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.

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 =>在构面饼图上添加标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆