2
votes

i am using gglot with facet_wrap to plot some data. The dimensions within the different facets are very different (0.2 vs. 2000).

I plot geom_bar and add geom_text with the same values above the bar. Now there is a problem. The geom_text value is for "big" bars under the headline.

I see two possible solutions, both i can not implement.

  1. Switch the geom_text position for big bars to plot inside. This could be done with vjust in the aes. But for every facet the switching point must be different.

  2. I would like to scale the y-axis to 110%, so there is space for the text. But i do not want to put it manually to my program, because the plot is done automaticaly.

enter image description here The code i used

library(ggplot2)
testdata <- data.frame(a = c(0.1,0.2,0.3, 4,5,6, 7000,8000,9000),
                   b = c('a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c' ),
                   c = c('aa', 'bb', 'cc', 'aa', 'bb', 'cc', 'aa', 'bb', 'cc'))

ggplot(testdata, aes(x = c, y = a)) +
  geom_bar(stat = 'identity') +
  geom_text(aes(label = a), vjust = -1) +  
  facet_wrap(~b, ncol=1, scales = 'free_y')
1
geom_text(aes(label = a), position = position_dodge(width = 1), vjust = 2, size = 3)Aleksandr
Thanks. I forgot to mention, the data is just an example. This is working well for quite "equal" data, where all bars are big enough for text. But if for example the 0.1 becomes 0.01 and the 7000 becomes 7, than it cannot be seen, anymore. In that case it would be good to have it over the bar. But how to do that with a different split point for every facet?user2083142

1 Answers

8
votes

Here is solution for you:

*(Have a look at this stackoverflow question and answer if you wanna know more details)

library(data.table)
testdata <- data.table(testdata)
testdata[,y_min:= a*0.5, by = c]
testdata[,y_max:= a*1.5, by = c]

ggplot(testdata, aes(x = c, y = a)) +
  geom_bar(stat = 'identity') +
  geom_text(aes(label = a), vjust = -1) + 
  facet_wrap(~b, ncol=1, scales = 'free_y') +
  geom_blank(aes(y = y_min)) +
  geom_blank(aes(y = y_max))

enter image description here

You need to at first create y_min and y_max variables for each group. And "plot" them via geom_blank().