Create labels in a side-by-side bar chart with coord flip in ggplot

I am trying to create labels for a side-by-side bar chart in R. I have flipped the coordinates. Here is an example,

x <- c("USA", "Canada", "Pakistan", "USA", "Canada", "Pakistan")
y <- c("FY18", "FY18", "FY18", "FY19", "FY19", "FY19")
z <- c(8, 9, 4, 3, 4, 10)

df <- data.frame(x, y, z)

p1 <- ggplot(df, aes(x = x, y = z, fill = y)) +
  geom_bar(stat = "identity", position = "dodge") +
  coord_flip()
p1

p2 <- p1 + annotate("text", x = df$x, 
               y = max(df$z) + 5, 
               label = df$z, 
               col = "black")
p2

Here is what the graph looks like :

enter image description here

I want the labels on the right side. But the labels are overlapping. I have tried multiple times to fix this but nothing seems to work. I have also tried to place labels on the bars but the positioning is off.

Here is actually what I am trying to create,

Here is actually what I am trying to create,

Since you are mapping a variable to an aesthetic (label = z in your example), then it is better to use geom_text() instead of annotate().

library(ggplot2)

df <- data.frame(
  stringsAsFactors = FALSE,
                 x = c("USA", "Canada", "Pakistan", "USA", "Canada", "Pakistan"),
                 y = c("FY18", "FY18", "FY18", "FY19", "FY19", "FY19"),
                 z = c(8, 9, 4, 3, 4, 10)
)

ggplot(df, aes(y = x, x = z, fill = y)) +
    geom_col(position = "dodge") +
    geom_text(aes(x = max(z) + 5, label = z),
              position = position_dodge(width = 1))

Created on 2020-08-16 by the reprex package (v0.3.0)

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