如何在ggplot R中的条形图顶部添加文本?

How to add text on the top of bar chart in ggplot R?

我已经构建了一个条形图,现在我有一个非常具体的需求。我想在条形顶部添加 diffperdiff 值,但找不到任何合适的方法。 另外,我想不间断地显示 x 比例,比如 0、25、50、100、125....

df <- data.frame (Origin = c("Canada", "Canada","USA","USA"),
                  Year = c("2021", "2022","2021","2022"),
                  Sales = c(103, 192, 144, 210),
                  diff = c(89, " ",66," "),
                  perdiff = c(86.4, " ",45.83," "))



ggplot(df, aes(fill=Year, y=Origin, x=Sales)) + 
    geom_bar(position="dodge", stat="identity") 

期望的结果:

添加了第 label 列以在绘图上进行标记。
顺便说一句,你想要的结果的标签被切换了。 (根据您的 df,加拿大为 89、46.4)。

require(ggplot2)
require(dplyr)

df <- data.frame (Origin = c("Canada", "Canada","USA","USA"),
                  Year = c("2021", "2022","2021","2022"),
                  Sales = c(103, 192, 144, 210),
                  diff = c(89, " ",66," "),
                  perdiff = c(86.4, " ",45.83," "))


df <- df %>% mutate(label= ifelse(diff!=" ",paste0(diff,", ",perdiff,'%'),NA))
ggplot(df, aes(fill=Year, y=Origin, x=Sales)) + 
  geom_bar(position="dodge", stat="identity")+
  geom_text(aes(label=label, x=200), fontface='bold') +
  scale_x_continuous(breaks=seq(0,200,25))+
  theme()
#> Warning: Removed 2 rows containing missing values (geom_text).

reprex package (v2.0.1)

于 2022-05-03 创建