【问题标题】:ggplot2: side by side barplot with one bar stacked and the other notggplot2:并排条形图,一个条堆叠,另一个不堆叠
【发布时间】:2015-05-04 01:39:09
【问题描述】:

我正在尝试创建一个条形图,其中为每个类别绘制两个条形图(并排):一个用于“总数”,另一个按子组堆叠。例如,在以下数据框中,“名称”将显示在 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)

【问题讨论】:

  • 您是要制作一个子组和总条相邻的图形,还是如您目前所描述的那样,背靠背?
  • 我希望它们彼此相邻...背靠背是我现在可以得到的(不使用构面)...抱歉造成混乱...

标签: r ggplot2 bar-chart


【解决方案1】:

您可以使用构面。看来您不能同时堆叠和躲闪(请参阅下面的相关帖子)。您可以在您的数据中为 x 变量和您的 names 变量的 facet 添加另一个因素,以得出类似这样的结果:

编辑:调整条的宽度以使条按 cmets 接触。见这里:Remove space between bars 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

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

ggplot2 - bar plot with both stack and dodge

ggplot2 geom_bar position = "dodge" does not dodge

Plotting a stacked bar plot?

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

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")

【讨论】:

  • 很高兴知道这个技巧,但我确实希望“nums”和“total”栏显示得尽可能接近。如果闪避和叠加都做不到,我肯定会用这个替代方案。谢谢!
  • 这看起来很棒!谢谢!
【解决方案2】:

您还可以增加条形的宽度以更好地适应图形。 试试这个:

 p = ggplot(df, aes(x=factor(names)), ) + 
  geom_bar(width=0.75,data=subset(df,num=="total"), aes(y=values), stat="identity",width=.5) +
  geom_bar( width=0.75, data=subset(df,num!="total"), aes(y=-values,fill=factor(num)), stat="identity",width=.5) 
print(p)

编辑:

我想我误解了你的问题。您希望一个名称中的条并排吗?

【讨论】:

  • 是的..我想要LJW生成的情节如下图,但我不想使用facet..据他说,似乎stack和dodge不能一起完成...不知道你是否知道怎么做...谢谢!
【解决方案3】:

我相信自从这些答案发布以来,ggplot2 包已经发生了变化。我正在使用 R 版本 4.0.2 和 ggplot2 版本 3.3.3。如果我按照您的要求进行操作,我相信 geom_bar 函数中的 stat='identity'position=position_dodge() 参数应该符合您的要求,至少它对我有用。

  ggplot(df, aes(names, values, fill=num))+
     geom_bar(stat='identity', position = position_dodge())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-03
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多