【发布时间】: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”选项冲突。任何帮助将不胜感激。
【问题讨论】: