Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten the alpha channel in ggplot2

Tags:

r

ggplot2

alpha

Some objects (functions) of ggplot2 support an alpha channel.

http://docs.ggplot2.org/current/geom_point.html

This is a nice feature, but transparent colours in pdf and png files are often source of diversified trouble.

How can I use the alpha option and get flattened pdf output files?

like image 934
Jonas Stein Avatar asked Dec 12 '12 21:12

Jonas Stein


1 Answers

I had ongoing problems with a large Latex doc created with knitr + ggplot that was perfectly readable on my mac but was unopenable for Windows users. After numerous attempts at optimizing and flattening the pdf, I finally isolated the issue to a single alpha-heavy plot. In my case, switching from pdf to png output made the difference (though, based on your question, it sounds like pngs may not solve your problem).

If you are using knitr, you can automatically create a png version by setting the global (or chunk-specific) image output option dev to "png" instead of the default of "pdf". Depending on the plot, this can shrink the size & complexity of an alpha-heavy ggplot significantly. I've had a 10x reduction in plot file size from ~700KB to ~70KB (some simpler plots may actually increase in size, though).

The trade-off is there is likely to be some loss of resolution for the plots. For circulating a draft by email or for certain types of plots this may be fine. If the loss of resolution is too great, consider adjusting the dpi of the output (though, of course, this will increase the file size but may still work better in cross-platform settings).

To set the global image output to "png" you could use code like this:

    library(knitr)
    opts_chunk$set(dev="png", dpi=200)

To set the output to "png" within a specific chunk (e.g., just the plot that is alpha-heavy), use the dev="png" option. The example below generates a regular, non-alpha heavy plot. With knitr + Latex, the include=FALSE option will prevent a pdf version from automatically being included (I'm not sure if this is necessary for RMarkdown).

    <<myplot, dev="png", dpi=200, include=FALSE>> 
    library(ggplot2)
    x <- 1:1000
    y <- 2*x + rnorm(1000, 0, 100)
    df <- data.frame(x,y)  
    ggplot(df, aes(x=x, y=y)) + geom_point(alpha=.3)
    @

The above code will generate a file called myplot.png which, in Latex, can then easily be included in the document with an includegraphics command nested in a figure environment.

    \begin{figure}[h!]
    \centering
    \scalebox{.5}{\includegraphics{myplot.png}}
    \caption{Some caption \label{fig:myplot}} 
    \end{figure}

Another resource that might be helpful is this blog post hosted at R Bloggers:

Fast-track publishing using knitr: exporting images for sharing and press

Also, see the Plots section of knitr options.

like image 52
Omar Wasow Avatar answered Nov 09 '22 17:11

Omar Wasow