如何在 GGplot2 中的条形图上添加百分号
how to add percentage sign on bars in GGplot2
我找了很久,没有任何提示帮助我,所以我要单独问一下。
我是 R 的初学者并编写了以下代码:
matchplayerNew <- match_player %>% group_by(civ, group = winner) %>%
summarize(count = n()) %>% # count records by winner
mutate(pct = count/sum(count)) # find percent of total
ggplot(matchplayerNew, aes(civ, pct, fill = group)) +
geom_bar(stat = "identity") +
geom_text(aes(label = sprintf("%0.2f", round((pct*100), digits = 2))), position = position_stack(vjust = .5), angle = 90) +
scale_y_continuous(labels = percent) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, size = 13)) +
scale_fill_manual("legend", values = c("Loose" = "royalblue3", "Win" = "darkorange2"))
这给了我以下情节:
Plot image
我现在想在每个条形和颜色中添加百分号。有什么建议吗?
提前致谢
你试过了吗:
geom_text(aes(label = percent (sprintf("%0.2f", round((pct*100), digits = 2))))
使用 scales::percent 完成。
或
geom_text(aes(label = paste0( sprintf("%0.2f", round((pct*100), digits = 2))), "%")
将 % 粘贴到标签的末尾
或
geom_text(aes(label = sprintf("%0.2f%%", round((pct*100), digits = 2)))
%% 在 sprintf 中插入文本
我找了很久,没有任何提示帮助我,所以我要单独问一下。 我是 R 的初学者并编写了以下代码:
matchplayerNew <- match_player %>% group_by(civ, group = winner) %>%
summarize(count = n()) %>% # count records by winner
mutate(pct = count/sum(count)) # find percent of total
ggplot(matchplayerNew, aes(civ, pct, fill = group)) +
geom_bar(stat = "identity") +
geom_text(aes(label = sprintf("%0.2f", round((pct*100), digits = 2))), position = position_stack(vjust = .5), angle = 90) +
scale_y_continuous(labels = percent) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, size = 13)) +
scale_fill_manual("legend", values = c("Loose" = "royalblue3", "Win" = "darkorange2"))
这给了我以下情节:
Plot image
我现在想在每个条形和颜色中添加百分号。有什么建议吗?
提前致谢
你试过了吗:
geom_text(aes(label = percent (sprintf("%0.2f", round((pct*100), digits = 2))))
使用 scales::percent 完成。
或
geom_text(aes(label = paste0( sprintf("%0.2f", round((pct*100), digits = 2))), "%")
将 % 粘贴到标签的末尾
或
geom_text(aes(label = sprintf("%0.2f%%", round((pct*100), digits = 2)))
%% 在 sprintf 中插入文本