首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ggplot生成具有按比例大小的饼的拼图

使用ggplot生成具有按比例大小的饼的拼图
EN

Stack Overflow用户
提问于 2021-03-08 05:41:46
回答 1查看 33关注 0票数 0

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

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

代码语言:javascript
复制
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中生成饼图,每个饼图的大小相同

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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

我想我可以看到是什么导致了这个问题,因为宽度参数最初会产生一个居中的条形图,当条形图投影到极坐标时,左边的空白会继续下去。

但是,我还没有找到解决办法。

谢谢

EN

回答 1

Stack Overflow用户

发布于 2021-03-08 06:32:35

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

代码语言:javascript
复制
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()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66521736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档