r - 使用 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
然后,当我尝试使用“宽度”参数生成与每棵树采样的错误总数成比例的饼图时,我得到了有意义的图,但在较小的饼图中有一个“洞”。
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
我想我可以看到导致问题的原因,因为 width 参数最初会产生一个居中的条形图,并且当条形图投影到极坐标时,左侧的空白会向前移动。
但是,我一直无法找到解决方法
谢谢
解决方案
这是一种使用 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()
推荐阅读
- android - 如何将树莓派流式传输到安卓系统
- php - 使用 Swift 使用 PHP 等效的正则表达式 (#\n\s*\n#Uis) 拆分字符串
- git - 创建不是 HEAD-less 但没有主分支的远程
- android - Android ResourcesNotFoundException 但是图像存在于所有可绘制文件夹中
- node.js - Nodejs 在另一个内部使用中间件
- c - 调试不进入循环
- nativescript - 无法打开开发工具
- python - CUDA GPU 的 Numba 代码编译失败并出现 OSError:异常:读取访问冲突
- r - 如何使用 R 计算多列的唯一值?
- php - PHP SimpleXMLElement - 在元素中访问值