rggplot2dplyrlimits

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!


Solution

  • 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)