显示频率 (%) 并在条形图上计数
Display frequency (%) and count on a bar chart
我有一个包含三列的数据框:
- 结果:因子变量(两行)
- n:整型变量,显示因子变量在数据框中出现的次数
freq: dbl 变量显示数据集中因子变量的频率
df <- data.frame(结果 = as.factor(c("Good", "Bad")),
n = c(700, 300), 频率 = c(70, 30))
我使用以下代码根据因子变量的频率创建条形图:
library(ggplot2)
ggplot(df, aes(x=outcome, y=freq, fill=outcome)) +
geom_bar(stat="identity", width=.4) +
geom_text(aes(label=paste0(freq,"%")), vjust=1.5, colour="white")
此代码在每个条的顶部显示频率,类似这样 70%
我想在条形图顶部同时显示频率和计数。类似于:70% (4532)
如果可能,在百分比和计数之间使用换行符。
知道如何实现吗?
ggplot(df, aes(x=outcome, y=freq, fill=outcome)) +
geom_bar(stat="identity", width=.4) +
geom_text(aes(label=paste0(freq, "%\n(", n, ")"), vjust=1.5, colour="white")
我有一个包含三列的数据框:
- 结果:因子变量(两行)
- n:整型变量,显示因子变量在数据框中出现的次数
freq: dbl 变量显示数据集中因子变量的频率
df <- data.frame(结果 = as.factor(c("Good", "Bad")), n = c(700, 300), 频率 = c(70, 30))
我使用以下代码根据因子变量的频率创建条形图:
library(ggplot2)
ggplot(df, aes(x=outcome, y=freq, fill=outcome)) +
geom_bar(stat="identity", width=.4) +
geom_text(aes(label=paste0(freq,"%")), vjust=1.5, colour="white")
此代码在每个条的顶部显示频率,类似这样 70%
我想在条形图顶部同时显示频率和计数。类似于:70% (4532)
如果可能,在百分比和计数之间使用换行符。
知道如何实现吗?
ggplot(df, aes(x=outcome, y=freq, fill=outcome)) +
geom_bar(stat="identity", width=.4) +
geom_text(aes(label=paste0(freq, "%\n(", n, ")"), vjust=1.5, colour="white")