0

Is there any way to position a label separately for each bar in ggplot2?

In descriptive pseudo-code that would be something like

geom_bar(bar 1) +
  geom_text(#bar 1) +
geom_bar(bar 2) +
  geom_text(#bar 2)
  • 1
    Possible duplicate of [How to put labels over geom\_bar in R with ggplot2](https://stackoverflow.com/questions/6455088/how-to-put-labels-over-geom-bar-in-r-with-ggplot2) – M-- Nov 08 '18 at 18:43
  • p.s. this [Search for the answer](https://www.google.com/search?q=put+a+text+for+each+geom+bar+in+r&rlz=1C1GCEA_enUS821US821&oq=put+a+text+for+each+geom+bar+in+r&aqs=chrome..69i57j33.5751j0j7&sourceid=chrome&ie=UTF-8) also brings up other related threads that may help you. Cheers. – M-- Nov 08 '18 at 18:44
  • Can you please refer to an example or draw one? I don't understand what you mean by "position a label separately" -- do you want them to be in different physical positions (not overlapping), or do you want them aligned differently? What is happening when you use a single `geom_text` call that is not what you want? – Jon Spring Nov 08 '18 at 18:45
  • @Jon Spring- see below. I needed to move the labels on the left-hand-side of my plot more to the left, and those on the right-hand-side more to the right. They can' – user3100205 Nov 08 '18 at 21:13

1 Answers1

0

One possible solution ...

# Grouping 1 has levels G1_A, G1_B
# Grouping 2 has levels G2_A, G2_B
# make plot for G1_A and both {G2_A, G2_B}

#  {label here} ============= | ================ {label here} 
#        {label here} ======= | =========== {label here}
#            {label here} === | ====== {label here}

# Init ggplot object
g <- ggplot(data = subset(testdf, grouping_1=="G1_A"),  aes(x=Layer, y=Number, fill=grouping_2))

# Layer data for G2_A 
g <- g + geom_bar(data = subset(testdf, grouping_2=="G2_A" & grouping_1=="G1_A") , stat = "identity")

# Layer data for G2_B 
g <- g + geom_bar(data = subset(testdf, grouping_2=="G2_B" & grouping_1=="G1_A") , stat = "identity")

g <- g + labs(title="G1_A", x =" ", y = "Number (x1000)") 

# Axes + ticks
g <- g + scale_y_continuous(breaks = seq(-270000, 80000, 25000), 
                     labels = paste0(as.character(c(seq(270, 0, -25), seq(5, 80, 25))) )  )

# Limits to make sure labels show well                   
g <- g + expand_limits(y=c(-310000,120000))

# Layer labels for G2_A (move to the left)
g <- g + geom_text(data = subset(testdf, grouping_2=="G2_A" & grouping_1=="G1_A"),
         aes(label=Reporting), vjust=+0.5, hjust=1.2, color="black", size=2.5)

# Layer labels for G2_B (move to the right)
g <- g + geom_text(data = subset(testdf, grouping_2=="G2_B" & grouping_1=="G1_A"),
         aes(label=Reporting), vjust=+0.5, hjust=-0.3, color="black", size=2.5)     

# Common. Add 90deg rotation here
g <- g + scale_fill_brewer(palette = "Set1") + 
         theme_minimal() + theme(axis.text.x = element_text(angle = 60)) + 
         coord_flip()