ggplot2:并排条形图,其中一个条形堆叠,另一个条形不堆叠

Vin*_*hen 6 r bar-chart ggplot2

我正在尝试创建一个条形图,其中对于每个类别,绘制两个条形图(并排):一个用于“总计”,另一个由子组堆叠。例如,在下面的数据框中,“名称”将显示在 x 轴上。对于“names”中的每个类别,一个条形将代表“total”的值,另一个将是一个堆叠条形,代表“aaa”、“bbb”和“ccc”的值。我设法获得了“背靠背”图,但我不知道如何将“闪避”位置应用于这种情况以使条形并排。

df = data.frame(names = rep(LETTERS[1:3], each=4), 
                num = c(rep(c("aaa","bbb","ccc","total"), 3)), 
                values = c(1,2,3,7,2,2,5,10,3,4,2,9)))
p = ggplot(df, aes(x=factor(names))) + 
    geom_bar(data=subset(df,num=="total"), aes(y=values), stat="identity",width=.5) +
    geom_bar(data=subset(df,num!="total"), aes(y=-values,fill=factor(num)), stat="identity",width=.5) 
print(p)
Run Code Online (Sandbox Code Playgroud)

小智 4

您可以使用方面。看来你不能同时堆叠和闪避(参见下面的相关帖子)。您可以向 x 变量的数据添加另一个因素,并在名称变量上添加构面,以得出如下结果:

编辑:调整条形宽度,使条形按照注释接触。请参阅此处:删除条形之间的空间 ggplot2

library(ggplot2)
p <- ggplot(data = df, aes(x = place, y = values, colour = num, fill = num))
p <- p + geom_bar(stat = "identity", width = 1, position = "stack")
p <- p + facet_grid(. ~ names)
p
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果您感兴趣的话,您似乎可以调整刻面的边距,使 ABC 组看起来更靠近。有关一些示例,请参阅这些相关帖子:

ggplot2 - 具有堆栈和闪避的条形图

ggplot2 geom_bar position = "dodge" 不闪避

绘制堆积条形图?

添加“地点”因素的编辑数据:

df <-    structure(list(names = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"), 
    num = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 
    3L, 4L), .Label = c("aaa", "bbb", "ccc", "total"), class = "factor"), 
    values = c(1, 2, 3, 7, 2, 2, 5, 10, 3, 4, 2, 9), position = structure(c(1L, 
    1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L), .Label = c("nums", 
    "total"), class = "factor")), .Names = c("names", "num", 
"values", "place"), row.names = c(NA, -12L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)