r - 如何使用 ggplot 创建百分比堆叠形状
问题描述
有没有办法可以用ggplot2
geom_rect()
图层做百分比堆积图?我有坐标,所以我创建了一个形状,我也有我的分离变量t
,现在我想根据t
. 换句话说,我想做百分比堆叠条形图,但不是条形图,而是自定义形状(在我的情况下,是简单的矩形)。我一直在尝试很多position="fill"
,stat="identity"
和他们的品种,但没有任何成功。我想知道这是否可能,如果可以,我该如何实现?
df <- structure(list(x1 = c(4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3,
3, 3), x2 = c(6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 4, 4, 4, 4, 4), y1 = c(3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1), y2 = c(5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 2, 2, 2, 2, 2), t = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 1L), .Label = c("a",
"b"), class = "factor")), row.names = c("1", "2", "3", "4", "5",
"6", "7", "8", "9", "10", "11", "12", "13", "14", "15"), class = "data.frame")
library(ggplot2)
ggplot() +
geom_rect(data=d, mapping=aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2, fill = t))
感谢您的时间!
解决方案
这是所需绘图的工作代码,它使用 进行了一些编码dplyr
,但它有效。
library(ggplot2)
library(tidyverse)
df1<-df %>%
group_by(x1,y1,x2,y2,t) %>%
count() %>%
ungroup() %>%
group_by(x1,y1) %>%
mutate(perc = n / sum(n),
percLabel = paste(100 * perc,"%",sep = " "),
transf = abs(x2-x1) * perc,
newx1 = ifelse(t == "a", x1,x2-transf),
newx2 = ifelse(t == "a", x1+transf,x2))
ggplot(df1,aes(xmin = newx1,
xmax = newx2,
ymin = y1,
ymax = y2,
fill = t)) +
geom_rect(col = "black") +
geom_text(aes(x = newx1 + ((newx2 - newx1)/2),
y = y1 + ((y2 - y1)/2),
label = percLabel)) +
labs(x="X",y="Y")
推荐阅读
- android - NoSuchMethodError: 类 Landroid/util/SparseArray 中没有包含 (I)Z 的虚拟方法;
- reactjs - 无法在 React Native 中导入本地照片。出现错误“这些文件都不存在:”
- flutter - 在另一个页面的异步匿名函数中使用初始化的字符串
- if-statement - 需要按等级过滤回复,去掉“错误”和不适用的回复
- prometheus - 平滑非计数器图
- python - Selenium 无法按索引遍历 div
- javascript - 是否可以通过补偿漂移使多个设备上的 setInterval 保持“同步”,还是我需要服务器同步?
- ios - Xamarin.IOS 插件,在 DLL 中查看捆绑资源
- c# - 将 PieChart 与 LiveCharts 和 WPF .NET Core 一起使用
- c# - 如何一次将数据插入和更新到 EF 多个表中