Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic ylim in ggplot2 using dplyr pipe

I want to create dynamic ylim values in a ggplot so that the ylim parameter is referencing to the value that dplyr is providing via a pipe. To illustrate the problem, please see a working (non-generic) code that I want to change into a (currently not working generic) code.

require(dplyr)
require(scales)
require(ggplot2)

x <- data.frame(name = c("A","B","C"), 
                value = c(2,4,6))

working non-generic code:

arrange(x[1:2, ], value) %>%
  ggplot(data=., aes(x=factor(name), y=value)) + 
  geom_bar(stat="identity") +
  scale_y_continuous(labels=comma, 
                     limits=c(0,max(arrange(x[1:2, ], value)$value) * 1.1))

not working generic code (call does not find value):

arrange(x[1:2, ], value) %>%
  ggplot(data=., aes(x=factor(name), y=value)) + 
  geom_bar(stat="identity") +
  scale_y_continuous(labels=comma, 
                     limits=c(0,max(value) * 1.1))

So the question is if there is any way to set the limits generally i.e. the part after the arrange will always be the same (I need to produce a lot of the same graphs with differing x i.e. different limits). Thanks!

like image 430
Triamus Avatar asked Mar 18 '15 12:03

Triamus


2 Answers

If you can live with using <<- and also don't mind using one additional variable, the following will preserve the pipeline and give you a dynamic ylim:

max_val <- 0
arrange(x[1:2, ], value) %>%
{ max_val <<- max(.$value) 
. } %>% 
  ggplot(data=., aes(x=factor(name), y=value)) + 
  geom_bar(stat="identity") +
  scale_y_continuous(labels=comma, 
                     limits=c(0, max_val * 1.1))
like image 140
hrbrmstr Avatar answered Sep 29 '22 14:09

hrbrmstr


You could plot a dummy point with zero size at your limit values. This isn't an especially pretty solution but it does seem to be fairly flexible. Code would look like

arrange(x[1:2, ], value) %>%
  ggplot(data=., aes(x=factor(name), y=value)) + 
  geom_bar(stat="identity") +
  geom_point(aes(x=c(name[1], name[1]), y = c(0, max(value)*1.1)), size=0) +
  scale_y_continuous(labels=comma)
like image 22
WaltS Avatar answered Sep 29 '22 12:09

WaltS