首页 > 解决方案 > 使用 ggplot 生成具有按比例大小的饼图的饼图

问题描述

我正在尝试使用 ggplot 创建一个系列饼图,其中每个单独图表的总饼图大小与总数字大小成正比。

为了概括这个问题,我创建了这个玩具数据集——其中对 4 棵树进行了错误采样,每棵树位于树冠的三个位置——上、中和下。

Tree_ID <- as.factor(c("Tree_1","Tree_1","Tree_1","Tree_2","Tree_2","Tree_2","Tree_3","Tree_3","Tree_3","Tree_4","Tree_4","Tree_4"))
Count_loc <- as.factor(c("Upper", "Middle", "Lower", "Upper", "Middle", "Lower", "Upper", "Middle", "Lower","Upper", "Middle", "Lower"))
Bugs_per_loc  <- c(75000,   20000, 5000,    700,    250,    50, 50, 30, 20, 4,  4,  4)
Bugs_per_tree <- c(100000, 100000, 100000, 1000, 1000, 1000, 100, 100, 100, 12, 12, 12)
Ppt_bugs_loc <- c(.75, .20, .05, .70, .25, .05, .50, .30, .20, .333, .333, .333)
Tree_bug_counts <- data.frame(Tree_ID, Count_loc, Bugs_per_loc, Bugs_per_tree,  Ppt_bugs_loc)

使用以下代码,我可以在 ggplot 中生成饼图,每个饼图大小相同

plot_1 <- ggplot(Tree_bugs, aes(x="", y=Ppt_bugs_loc,  fill=Count_loc)) + 
  geom_bar(stat="identity") + 
  facet_wrap(Tree_ID, ncol=2)   + 
  coord_polar("y", start=0) +
  theme_void()
plot_1

图 1 - 饼图大小固定的饼图

然后,当我尝试使用“宽度”参数生成与每棵树采样的错误总数成比例的饼图时,我得到了有意义的图,但在较小的饼图中有一个“洞”。


plot_2 <- ggplot(Tree_bugs, aes(x="", y=Ppt_bugs_loc, fill=Count_loc, width=log10(Bugs_per_tree))) +
  geom_bar(stat="identity") + 
  facet_wrap(Tree_ID, ncol=2)   + 
  coord_polar("y", start=0) +
  theme_void()
plot_2

情节 2 - 饼图大小成比例

我想我可以看到导致问题的原因,因为 width 参数最初会产生一个居中的条形图,并且当条形图投影到极坐标时,左侧的空白会向前移动。

但是,我一直无法找到解决方法

谢谢

标签: rggplot2chartspie-chart

解决方案


这是一种使用 geom_rect 并预先计算每棵树内的堆叠的方法:

Tree_bug_counts %>%
  group_by(Tree_ID) %>%
  arrange(Tree_ID, Count_loc) %>%
  mutate(cuml_pct = cumsum(Ppt_bugs_loc)) %>%
  ungroup() %>%
  
  ggplot(aes(xmin=0, xmax = log10(Bugs_per_tree),
             ymin=cuml_pct - Ppt_bugs_loc, ymax = cuml_pct,
             fill=Count_loc)) + 
  geom_rect() +
  facet_wrap(Tree_ID, ncol=2)   + 
  coord_polar("y", start=0) +
  theme_void()

在此处输入图像描述


推荐阅读