0
df <- data.frame(x=c("A","C","D","A","A","B","C","D"), g=c("G1","G1","G1","G2","G3","G3","G3","G3"))

g <- ggplot(df, aes(x))
g + geom_bar() + geom_text(aes(y=g, label=g), vjust=-1)

The y axis labels are showing the group numbers instead of counts. I would also like to plot the text just above each bar without the huge gap between groups, for example for the first bar:

G3   
G2
G1

Is there a way I can fix these two points?

HappyPy
  • 9,839
  • 13
  • 46
  • 68

1 Answers1

2

You don't want groups on the y-axis, so don't use y = g.

We'll use position = position_stack() for the text layer setting a group aesthetic so it know what to stack. We can give a y value of 1 to stack up counts just like the bars:

ggplot(df, aes(x)) +
  geom_bar() + 
  geom_text(aes(x = x, label = g, group = g, y = 1), 
            vjust=-1, position = position_stack())

enter image description here

If you want the labels closer together, you can use a smaller y value. How it looks will depend on the resolution of your final plot.

ggplot(df, aes(x)) +
  geom_bar() + 
  geom_text(aes(x = x, label = g, group = g, y = .2), 
            vjust=-1, position = position_stack())

enter image description here

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294