R ggplot2 堆叠条形图,y 轴上的百分比,以条形计数

标签 r ggplot2

我在格式化 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 轴上没有百分比的图:

bar plot 1

绘图的第二个版本在 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")

bar plot 2

但我无法让它同时执行这两项操作。我没有浪费空间,而是在“aes”语句中尝试了“label=cfreq”,但没有成功——似乎与“geom_text”选项冲突。任何帮助将不胜感激。

最佳答案

这似乎可以满足您的要求:

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

Stacked labels

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

关于R ggplot2 堆叠条形图,y 轴上的百分比,以条形计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51215221/

相关文章:

r - 通过在 R 中注释使用来自 ggplot2 图形的默认填充颜色

r - 在 R 中绘制时间序列(24 小时)

r - 在示例部分保留缩进

r - 如何交叉引用 R 帮助文件/roxygen2 中的方程

r - 使用 ggplot2 出现意外的 Walker 别名表输出

r - 指示最大值并在 ggplot 上添加相应的标签

R数据.表: how to use R variables that contain column names?

r - R 和 Scala Breeze 之间傅里叶逆变换的差异

R函数将一天中的时间转换为总分钟数

r - 如何在ggplot中绘制高于和低于零的值的密度?