首页 > 解决方案 > 如何使用 ggplot 输入 2 位数的条形图百分比 (%)?

问题描述

我没有很多 R 技能,我有两个问题。有人可以帮我吗?

a) 我想在这个图中用两位数(120,07%)输入百分比数字。我一直在尝试使用“dplyr”,但我做不到。

b)那么,我可以用图形中的百分比更改“y 轴”吗?

谢谢!

library(ggplot2)
ggplot(place, aes(x = Place, y = Dif)) +
  geom_bar(aes(fill = Dif < 0), colour="black", stat = "identity") +
  scale_fill_manual(guide = FALSE, breaks = c(TRUE, FALSE), values=c("gray", "red")) +
  geom_text(aes(label=Dif), position=position_dodge(width=0.9), vjust=-0.25)
structure(list(Place = c("Supermarket", "Markets", 
"House", "Consumption", "Hipermarkets", "Comerce", 
"Outdoors sale"), Dif = c(-20.1884514229122, -50.0150282227513, 
5.34342366569214, -2.47231788994851, 25.7466309314144, 120.078289871755, 
24.0501027574048)), row.names = c(NA, -7L), class = c("tbl_df", 
"tbl", "data.frame"))

在此处输入图像描述

标签: rggplot2geom-bar

解决方案


你可以这样做:

library(ggplot)

ggplot(df, aes(Place, Dif/100, fill = Dif > 0)) + 
  geom_col() +
  geom_text(aes(y = Dif/100 + 0.1 * sign(Dif/100),
                label = scales::percent(Dif/100))) +
  geom_hline(yintercept = 0) +
  scale_fill_manual(values = c("red", "forestgreen"), guide = guide_none()) +
  scale_y_continuous(labels = scales::percent, name = "Diff") +
  theme_bw()

在此处输入图像描述


推荐阅读