如何将频率百分比添加到 ggplot2 中的有序条形图
How to add frequency percentages to a ordered barplot in ggplot2
我需要构建一个水平条形图,它是有序的并且在其顶部(侧面)具有频率计数(我可以获得)以及频率百分比。到目前为止,我的代码看起来像这样。我无法订购图表或添加百分比(除了计数)。任何帮助深表感谢。很抱歉,我是新来的,没有足够的声誉来 post 示例图片。
event <- c("a","a","a","a","a","a","b","b","b","b","c","c","c","c","c")
dat <- data.frame(event)
ggplot(dat, aes(x=event)) + geom_bar(fill = "orange", width = 0.5) + coord_flip() +
geom_text(stat='bin',aes(label=..count..,vjust=.75, hjust = 0))
感谢帮助
可以通过预先更改因子来更改顺序:
dat$event <- factor(dat$event, levels = names(sort(table(dat$event)))).
添加百分比就像添加绝对值一样:
geom_text(stat='bin',
aes(label=paste0(..count..,
", ",
round(..count../sum(..count..)*100, 1),
"%")))
我需要构建一个水平条形图,它是有序的并且在其顶部(侧面)具有频率计数(我可以获得)以及频率百分比。到目前为止,我的代码看起来像这样。我无法订购图表或添加百分比(除了计数)。任何帮助深表感谢。很抱歉,我是新来的,没有足够的声誉来 post 示例图片。
event <- c("a","a","a","a","a","a","b","b","b","b","c","c","c","c","c")
dat <- data.frame(event)
ggplot(dat, aes(x=event)) + geom_bar(fill = "orange", width = 0.5) + coord_flip() +
geom_text(stat='bin',aes(label=..count..,vjust=.75, hjust = 0))
感谢帮助
可以通过预先更改因子来更改顺序:
dat$event <- factor(dat$event, levels = names(sort(table(dat$event)))).
添加百分比就像添加绝对值一样:
geom_text(stat='bin',
aes(label=paste0(..count..,
", ",
round(..count../sum(..count..)*100, 1),
"%")))