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

Time:05-03

I have built a bar chart and now I have a very specific need. I want to add diff and perdiff values on on the top of bars, but could not find any suitable way for that. Also, I want to show x-scale without breaks, like 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") 

Desired outcome: enter image description here

CodePudding user response:

Column label was added for labeling on the plot.
BTW, the label of your desired outcome is switched. (According to your df, 89, 46.4 for Canada).

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).

Created on 2022-05-03 by the reprex package (v2.0.1)

  • Related