使用 ggplot2 1.0.0
,我按照以下帖子中的说明来弄清楚如何绘制因子之间的百分比条形图:
Sum percentages for each facet - respect "fill"
test <- data.frame(
test1 = sample(letters[1:2], 100, replace = TRUE),
test2 = sample(letters[3:8], 100, replace = TRUE)
)
library(ggplot2)
library(scales)
ggplot(test, aes(x= test2, group = test1)) +
geom_bar(aes(y = ..density.., fill = factor(..x..))) +
facet_grid(~test1) +
scale_y_continuous(labels=percent)
但是,当使用 geom_text
时,我似乎无法获得总计数或每个条形图上方的百分比的标签 .
上述代码的正确添加是什么,也保留了y轴的百分比?
3 回答
留在ggplot中,你可能会尝试
对于计数,请在geom_bar和geom_text中将..density ..更改为..count ..
UPDATE for ggplot 2.x
ggplot2 2.0
对ggplot
做了很多更改,包括在更改geom_bar
ggplot 2.0.0使用的默认stat
函数时破坏了此代码的原始版本的更改 . 它不像以前一样调用stat_bin
来分组数据,而是调用stat_count
来计算每个位置的观察值 .stat_count
返回prop
作为该位置的计数比例而不是density
.下面的代码已经过修改,可以使用
ggplot2
的新版本 . 我've included two versions, both of which show the height of the bars as a percentage of counts. The first displays the proportion of the count above the bar as a percent while the second shows the count above the bar. I' ve还为y轴和图例添加了标签 .第一个版本的情节如下所示 .
如果您预先汇总数据,这会更容易 . 例如:
(仅供参考,您也可以将标签放在条形图中,例如,将最后一行代码更改为:
y=pct*0.5), size=4, colour="white")
)我已经使用了所有代码并提出了这个问题 . 首先将你的ggplot分配给一个变量,即p < - ggplot(...)geom_bar(...)等 . 然后你可以这样做 . 你不需要总结很多,因为ggplot有一个构建函数,它已经为你提供了所有这些 . 我会留给你格式化等等 . 祝好运 .