【问题标题】:R ggplot2 stacked barplot, percent on y axis, counts in barsR ggplot2堆积条形图,y轴百分比,条形计数
【发布时间】:2018-12-15 08:20:35
【问题描述】:

我在格式化 ggplot2 以显示堆积条形图时遇到问题,该条形图在 Y 轴上具有累积百分比并在条形内计数。我可以为每种类型绘制一个图(一个在 Y 轴上显示百分比,一个在条形图中显示计数),但不能同时绘制两者。这是我所拥有的:

group <- c(1,1,1,2,2,2)
ind <- c(1,2,3,1,2,3)
count <- c(98,55,10,147,31,3)
df <- data.frame(group, ind, count)

library(ggplot2)
library(scales)

ggplot(df, aes(y=count, x=factor(group), fill=factor(ind), label=cfreq)) +
geom_bar(stat = "identity") + ylab("Percent Level 1 Classes") +
scale_fill_discrete(name="Level 1\nClasses") +
xlab("Level 2 Groups") +
geom_text(size = 3, position = position_stack(vjust = 0.5))

这会产生以下图,其中 Y 轴上有计数但没有百分比:

图的第二个版本在 Y 轴上产生百分比,但在条形图中没有计数:

ggplot(df, aes(y=count, x=factor(group), fill=factor(ind))) +
geom_bar(position = "fill", stat = "identity") + 
ylab("Percent Level 1 Classes") +
scale_fill_discrete(name="Level 1\nClasses") +
xlab("Level 2 Groups")

但我不能同时做到这两点。我没有浪费空间,而是在“aes”语句中尝试了“label=cfreq”,但无济于事——似乎与“geom_text”选项冲突。任何帮助将不胜感激。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这似乎是你想要的:

    group <- c(1,1,1,2,2,2)
    ind <- c(1,2,3,1,2,3)
    count <- c(98,55,10,147,31,3)
    df <- data.frame(group, ind, count)
    
    library(ggplot2)
    library(scales)
    
    ggplot(df, aes(y=count, x=factor(group), fill=factor(ind))) +
      geom_bar(position = "fill", stat = "identity") +
      geom_text(aes(label = count), position = position_fill(vjust = 0.5)) +
      ylab("Percent Level 1 Classes") +
      scale_fill_discrete(name="Level 1\nClasses") +
      xlab("Level 2 Groups")
    

    我认为默认情况下,位置设置为“身份”,而“堆栈”也不能解决问题,因为标签似乎是原始的计数比例,而不是百分比,所以条形图缩小了基本上是情节底部的一条线。使用 vjust = 0.5 将标签居中,因为默认值为 1,这会将它们放在条形的顶部。

    【讨论】:

    • 谢谢!这正是发生的事情:条形被缩小到情节的底部。