title: How to rasterize a single layer of a ggplot?
body: <p>Matplotlib allows to rasterize individual elements of a plot and save it as a mixed pixel/vector graphic (<code>.pdf</code>) (see e.g. <a href="https://stackoverflow.com/a/5638626/1870254">this answer</a>). How can the same achieved in <code>R</code> with <code>ggplot2</code>?</p>
  <hr />
  <p>The following is a toy problem in which I would like to rasterize only the <code>geom_point</code> layer.</p>
  <pre><code>set.seed(1)
  x &lt;- rlnorm(10000,4)
  y &lt;- 1+rpois(length(x),lambda=x/10+1/x)
  z &lt;- sample(letters[1:2],length(x), replace=TRUE)
  
  p &lt;- ggplot(data.frame(x,y,z),aes(x=x,y=y)) +
    facet_wrap(&quot;z&quot;) +
    geom_point(size=0.1,alpha=0.1) +
    scale_x_log10()+scale_y_log10() +
    geom_smooth(method=&quot;gam&quot;,formula = y ~ s(x, bs = &quot;cs&quot;))
  print(p)
  ggsave(&quot;out.pdf&quot;, p)
  </code></pre>
  <p>When saved as <code>.pdf</code> as is, Adobe reader DC needs ~1s to render the figure. Below you can see a <code>.png</code> version:
  <a href="https://i.stack.imgur.com/5XTfm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5XTfm.png" alt="out.png" /></a></p>
  <p>Of course, it is often possible to avoid the problem by not plotting raw data</p>