1
votes

I am new to ggplot2 and on my first try ran into a problem that is not obvious to solve:

x <- data.frame(y = c(1,1,1,2,2,3,rep(c(1,2,3,4), 10)))

ggplot(x, aes(factor(y))) +
  geom_bar(fill = 2) +
  geom_text(stat="bin", aes(label = ..count..))

ggplot(x, aes(factor(y))) +
  geom_bar(fill = 2) +
  geom_text(aes(y = 5, label = y))

I can either have bar plot with correct number of observations but can not set y value to adjust positions. Or I can adjust positions but can not set labels to count number of observations.

Expected result is midpoint of both - have values of graph one in positions set in graph two.

Even better, can I set y positions for every geom_text value (e.g. mid-bar for tall bar, then above bar for short bar)?

1

1 Answers

2
votes

Something like this?

ggplot(x, aes(factor(y))) +
  geom_bar(fill = 2) +
  geom_text(stat="bin", aes(label = ..count.., y=(..count..-..count..)+5))

enter image description here

You can modify the aes() for each geom_ and you can actually supply a whole new data= parameter to each geom_ if you want special information on that layer.