首页 文章

ggplot2:并排的条形图,其中一个条形堆叠而另一条条形图没有

提问于
浏览
2

我正在尝试创建一个条形图,其中对于每个类别,绘制两个条形图(并排):一个用于“总计”,另一个用于子组 . 例如,在以下数据框中,“名称”将显示在x轴上 . 对于“名称”中的每个类别,一个条形将表示“总计”的值,另一个条形图表示来自“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)

2 回答

  • 2

    你可以使用facet . 看来你不能同时堆叠和躲闪(见下面的相关帖子) . 你可以为你的数据中的x变量和facet添加另一个因子来得到类似这样的东西:

    编辑:根据评论调整条形的条形宽度 . 见这里: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
    

    enter image description here

    看起来您可以调整构面的边距,以便在您感兴趣时让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")
    
  • 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)
    

    New plot

    EDIT:

    我想我误解了你的问题 . 你想要一个名字中的条形并排吗?

相关问题