Adding label in the center of the bar in geom_bar

Dear colleagues,

I am trying to get the label in the center of each bar in the following barplot.Please see attached image.

Here is the code I am using for this purpose,

p <- ggplot(top4_rev_comparison, aes(x=CARD_ORDINAL_NBR, y=TOTAL_DEMAND)) + 
  geom_bar(stat='identity',aes(fill=COHORT_NM),position=position_dodge())+
  scale_y_continuous( labels = scales::comma)+
    labs(title="Total Revenue Earned For Doors 1 thru 4 Across Test \n and Control",caption="Data between Nov. 14, 2019 and Nov. 17, 2019",x="Door Number",
       y="Total Revenue")+
  geom_text(aes(label = round(TOTAL_DEMAND)),
    position = position_dodge(0.9))+
  coord_flip()
p

Can I kindly get some help on how to align my text properly? Help is appreciated.

Can you please share a small part of the data set in a copy-paste friendly format?

In case you don't know how to do it, there are many options, which include:

  1. If you have stored the data set in some R object, dput function is very handy.

  2. In case the data set is in a spreadsheet, check out the datapasta package. Take a look at this link.

nudge_x might get you what you want. Below is an example with invented data. Please do learn how to include data with your questions. It saves a lot of work.

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.5.3
DF <- data.frame(Name = c("A", "A", "B", "B", "C", "C"),
                 TotalDemand = c(27,23,16,9, 32, 40),
                 Pop = c("TEST", "CONTROL", "TEST", "CONTROL", "TEST", "CONTROL"))
ggplot(DF, aes(x = Name, y = TotalDemand, fill = Pop)) + 
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(aes(label = TotalDemand, y = TotalDemand - 3), nudge_x = c(0.22, -0.22)) + 
  coord_flip()

Created on 2019-11-30 by the reprex package (v0.3.0.9000)

1 Like

Working with the sample data provided by FJCC, your code could work if you define the fill aesthetic globally (or if you define the group aesthetic on geom_text()), see this example.

library(ggplot2)

DF <- data.frame(Name = c("A", "A", "B", "B", "C", "C"),
                 TotalDemand = c(27,23,16,9, 32, 40),
                 Pop = c("TEST", "CONTROL", "TEST", "CONTROL", "TEST", "CONTROL"))

ggplot(DF, aes(x = Name, y = TotalDemand, fill = Pop)) + 
    geom_bar(stat = "identity", position = position_dodge()) +
    geom_text(aes(label = TotalDemand, y = TotalDemand - 3),
              position = position_dodge(width = 0.9)) + 
    coord_flip()

1 Like

Thanks for the help, colleagues. Highly appreciate it.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.