gpt4 book ai didi

r - ggplot2 - 不同宽度的堆叠条

转载 作者:行者123 更新时间:2023-12-04 11:44:58 25 4
gpt4 key购买 nike

我想生成一个反向金字塔图,其中条形以不同的宽度相互堆叠。

第一,我有一个堆积条形图,如下面的代码示例

library(dplyr)
library(ggplot2)
sample <- data_frame(x=c(1, 1, 1, 1, 2, 2, 2, 2),
y=c(5,10,15, 20, 10, 5, 20, 10),
w=c(1, 2, 3, 4, 1, 2, 3, 4),
group=c("a", "b", "c", "d", "a", "b", "c", "d"))

ggplot() +
geom_bar(data=sample,
aes(x=x,y=y,group=group, fill=group),
stat="identity", position=position_stack())

enter image description here

然后我将宽度添加到 aes所以较低的 w当它们仍然相互堆叠时,值(value)会更小。然而,这些条形并没有与警告叠加。
ggplot() +
geom_bar(data=sample,
aes(x=x,y=y,group=group, fill=group, width=w/5),
stat="identity", position=position_stack())

enter image description here
Warning: Ignoring unknown aesthetics: width
Warning message:
position_stack requires non-overlapping x intervals

任何有助于使条形图堆叠或可以涵盖类似概念的不同绘图类型的想法都将受到高度赞赏。谢谢!

最佳答案

这有点像黑客。

我会用 geom_rect()而不是真正的列。因此我需要创建 data.frame()预先计算矩形边界的位置。

df_plot <- sample %>% 
arrange(desc(group)) %>% # Order so lowest 'groups' firtst
group_by(x) %>%
mutate(yc = cumsum(y), # Calculate position of "top" for every rectangle
yc2 = lag(yc, default = 0) ,# And position of "bottom"
w2 = w/5) # Small scale for width


# Plot itself

ggplot(df_plot) +
geom_rect(
aes(xmin = x - w2 / 2, xmax = x + w2 / 2,
ymin = yc, ymax = yc2,
group = group, fill=group))

结果图:
enter image description here

关于r - ggplot2 - 不同宽度的堆叠条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45691362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com