如何使用 ggplot 创建百分比堆叠形状
How to create percent stacked shape with 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")
有什么方法可以用 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")