[英]Adding count and percent to bars ggplot
我已在條形頂部添加計數,但無法弄清楚如何在計數旁邊的括號中添加 %! 我的嘗試在條形上方的計數旁邊返回prop*100
。 這是我只生成計數的代碼 - 我需要對此進行什么修改才能添加 %?
df %>%
ggplot(aes(x = day_of_week, fill = day_of_week)) +
geom_bar(position = "dodge") +
geom_text(aes(label = ..count..), stat = "count", vjust = -1.0, colour = "black") +
ylim(0, 2600) +
theme_classic() +
theme(legend.position="none",
axis.text.x = element_text(angle=45, hjust=1)
) +
scale_fill_brewer(palette = 1, direction = - 1) +
xlab("day_of_week") +
ylab("Count (n)")
我最終創建了一個新的列,計算了每個感興趣的類別並運行了下面的代碼!
df2 <- df %>%
select(day_of_week) %>%
group_by(day_of_week) %>%
mutate(count_day_of_week_group = n()) %>%
ungroup
df2 <- df2 %>%
distinct(count_day_of_week_group, .keep_all = TRUE)
ggplot(df2, aes(x = day_of_week, y = count_day_of_week_group)) +
geom_bar(stat = "identity", color = "black", fill = "dodgerblue1") +
geom_text(label = with(df2,
sprintf("%d (%.0f%%)",
count_day_of_week_group, 100*count_day_of_week_group/sum(count_day_of_week_group))),
vjust=-1)+
ylim(0,3000)
這是一個不創建新列的選項:
df %>%
ggplot(aes(x = day_of_week, fill = day_of_week)) +
geom_bar(position = "dodge") +
geom_text(aes(label = paste0(..count..,"(",round(..count..*100/nrow(df)), "%)")), stat = "count", vjust = -1.0, colour = "black") +
ylim(0, 2600) +
theme_classic() +
theme(legend.position="none",
axis.text.x = element_text(angle=45, hjust=1)
) +
scale_fill_brewer(palette = 1, direction = - 1) +
xlab("day_of_week") +
ylab("Count (n)")
這是一個在 plot 之前創建的新列的選項:
df %>% group_by(day_of_week) %>%
summarise(n =n())%>%
mutate(pct= round(n/sum(n)*100, digit=0))%>%
ggplot(aes(x = day_of_week, y = n, fill = day_of_week)) +
geom_bar(stat = "identity") +
geom_text(aes(label = paste0(n, " (",pct, "%)")), vjust = -1.0, colour = "black") +
ylim(0, 2600) +
theme_classic() +
theme(legend.position="none",
axis.text.x = element_text(angle=45, hjust=1)
) +
scale_fill_brewer(palette = 1, direction = - 1) +
xlab("day_of_week") +
ylab("Count (n)")
set.seed(14)
df = data.frame(day_of_week = factor(sample(c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"),
size = 3000,
prob = c(1,3,5,2,6,10,1),
replace = TRUE), levels = c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.