title: How to dynamically axis scale limit for aes in ggplot?
body: <p>I am trying to annotate a ggplot histogram with a shaded rectangle, and am trying to figure out if there is a way to pass an argument to <code>ymax</code> that will dynamically scale the rectangle to the <code>ymax</code> of the plotting area.</p>
  
  <p>I can achieve the desired effect by hard coding the ymax value of the <code>annotate()</code> to be greater than the plot <code>ymax</code> then 'cropping' back the plot using <code>coord_cartesian()</code> shown in the example below. However, this requires me to know a priori what the max of the histogram will be, which of course will change if I adjust <code>binwidth</code>. There is some way to scale <code>ymax</code> dynamically?</p>
  
  <pre><code>ggplot(
    data = mtcars,
    aes(
      x=mpg
    )
   )+
    geom_histogram(
      binwidth = 3,
      fill = "gray63"
    )+
    annotate(
      "rect",
      xmin = 21,
      xmax = 22,
      ymin = 0,
      ymax = 10, #hardcode ymax to be &gt; plot ymax
      fill = "gray18",
      alpha = 0.5
    )+
    theme_bw()
    coord_cartesian(
      ylim = c(0,8) #crop back to plot ymax
    )
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/SnN4f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SnN4f.png" alt="example plot"></a></p>