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