Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot with facet scale and dynamic geom_text position

Tags:

r

ggplot2

facet

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')
like image 452
user2083142 Avatar asked Dec 06 '25 09:12

user2083142


1 Answers

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().

like image 137
Mal_a Avatar answered Dec 10 '25 01:12

Mal_a



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!