<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/using-r-a-function-that-adds-multiple-ggplot2-layers/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://martinsbioblogg.wordpress.com/2017/04/23/using-r-a-function-that-adds-multiple-ggplot2-layers/"> R – On unicorns and genes</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Another interesting thing that an R course participant identified: Sometimes one wants to make a function that returns multiple layers to be added to a ggplot2 plot. One could think that just adding them and returning would work, but it doesn’t. I think it has to do with how + is evaluated. There are a few workarounds that achieve similar results and may save typing.</p>
<p>First, some data to play with: this is a built-in dataset of chickens growing:</p>
<pre>
library(ggplot2)

data(ChickWeight)
diet1 &lt;- subset(ChickWeight, Diet == 1)
diet2 &lt;- subset(ChickWeight, Diet == 2)
</pre>
<p>This is just an example that shows the phenomenon. The first two functions will work, but combining them won’t.</p>
<pre>
add_line &lt;- function(df) {
  geom_line(aes(x = Time, y = weight, group = Chick), data = df)
}

add_points &lt;- function(df) {
  geom_point(aes(x = Time, y = weight), data = df)
}

add_line_points &lt;- function(df) {
  add_line(df) + add_points(df)
}

## works
(plot1 &lt;- ggplot() + add_line(diet1) + add_points(diet1))

## won't work: non-numeric argument to binary operator
try((plot2 &lt;- ggplot() + add_line_points(diet1)))
</pre>
<p><a target="_blank" rel="nofollow" href="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot1.png"><img sizes="(max-width: 480px) 100vw, 480px" data-image-description="" data-orig-file="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot1.png?w=456" data-orig-size="480,480" data-image-title="blog_plot1" class="wp-image-5235" data-comments-opened="1" data-recalc-dims="1" data-attachment-id="5235" data-permalink="https://martinsbioblogg.wordpress.com/2017/04/23/using-r-a-function-that-adds-multiple-ggplot2-layers/blog_plot1/#main" alt="" data-medium-file="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot1.png?w=456?w=300" data-large-file="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot1.png?w=456?w=480" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot1.png?w=456"></a></p>
<p>First, you can get the same result by putting mappings and data in the ggplot function. This will work if all layers are going to plot the same data, but that does it for some cases:</p>
<pre>
## bypasses the issue by putting mappings in ggplot()
(plot3 &lt;- ggplot(aes(x = Time, y = weight, group = Chick), data = diet1) +   
  geom_line() + geom_point())
</pre>
<p>One way is to write a function that takes the plot object as input, and returns a modified version of it. If we use the pipe operator %>%, found in the magrittr package, it even gets a ggplot2 like feel:</p>
<pre>
## bypasses the issue and gives a similar feel with pipes

library(magrittr)

add_line_points2 &lt;- function(plot, df, ...) {
  plot +
    geom_line(aes(x = Time, y = weight, group = Chick), ..., data = df) +
    geom_point(aes(x = Time, y = weight), ..., data = df)
}

(plot4 &lt;- ggplot() %>% add_line_points2(diet1)
   %>% add_line_points2(diet2, colour = &quot;red&quot;))
</pre>
<p><a target="_blank" rel="nofollow" href="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot4.png"><img sizes="(max-width: 480px) 100vw, 480px" data-image-description="" data-orig-file="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot4.png?w=456" data-orig-size="480,480" data-image-title="blog_plot4" data-comments-opened="1" class="wp-image-5236" data-recalc-dims="1" data-attachment-id="5236" data-permalink="https://martinsbioblogg.wordpress.com/2017/04/23/using-r-a-function-that-adds-multiple-ggplot2-layers/blog_plot4/#main" alt="" data-medium-file="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot4.png?w=456?w=300" data-large-file="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot4.png?w=456?w=480" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot4.png?w=456"></a></p>
<p>Finally, in many cases, one can stick all the data in a combined data frame, and avoid building up the plot from different data frames altogether.</p>
<pre>
## plot the whole dataset at once
(plot5 &lt;- ggplot(aes(x = Time, y = weight, group = Chick, colour = Diet),
                 data = ChickWeight) +
   geom_line() + geom_point())
</pre>
<p><a target="_blank" rel="nofollow" href="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot5.png"><img sizes="(max-width: 480px) 100vw, 480px" data-image-description="" data-orig-file="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot5.png?w=456" data-orig-size="480,480" data-image-title="blog_plot5" data-comments-opened="1" class="wp-image-5237" data-recalc-dims="1" data-attachment-id="5237" data-permalink="https://martinsbioblogg.wordpress.com/2017/04/23/using-r-a-function-that-adds-multiple-ggplot2-layers/blog_plot5/#main" alt="" data-medium-file="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot5.png?w=456?w=300" data-large-file="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot5.png?w=456?w=480" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://martinsbioblogg.files.wordpress.com/2017/04/blog_plot5.png?w=456"></a></p>
<p>Okay, maybe that plot is a bit too busy to be good. But note how the difference between plotting a single diet and all diets at the same time one more mapping in aes(). No looping or custom functions required.</p>
<p>I hope that was of some use.</p>
<p>Postat i:<a target="_blank" rel="nofollow" href="https://martinsbioblogg.wordpress.com/category/computer-stuff/">computer stuff</a>, <a target="_blank" rel="nofollow" href="https://martinsbioblogg.wordpress.com/category/data-analysis/">data analysis</a> Tagged: <a target="_blank" rel="nofollow" href="https://martinsbioblogg.wordpress.com/tag/ggplot2/">ggplot2</a>, <a target="_blank" rel="nofollow" href="https://martinsbioblogg.wordpress.com/tag/r/">R</a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/martinsbioblogg.wordpress.com/5078/"><img alt="" src="http://feeds.wordpress.com/1.0/delicious/martinsbioblogg.wordpress.com/5078/" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/martinsbioblogg.wordpress.com/5078/"><img alt="" src="http://feeds.wordpress.com/1.0/facebook/martinsbioblogg.wordpress.com/5078/" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/martinsbioblogg.wordpress.com/5078/"><img alt="" src="http://feeds.wordpress.com/1.0/twitter/martinsbioblogg.wordpress.com/5078/" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/martinsbioblogg.wordpress.com/5078/"><img alt="" src="http://feeds.wordpress.com/1.0/stumble/martinsbioblogg.wordpress.com/5078/" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/martinsbioblogg.wordpress.com/5078/"><img alt="" src="http://feeds.wordpress.com/1.0/digg/martinsbioblogg.wordpress.com/5078/" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/martinsbioblogg.wordpress.com/5078/"><img alt="" src="http://feeds.wordpress.com/1.0/reddit/martinsbioblogg.wordpress.com/5078/" border="0"></a> <img alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://martinsbioblogg.wordpress.com/2017/04/23/using-r-a-function-that-adds-multiple-ggplot2-layers/"> R – On unicorns and genes</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/Tby9hmIs-LM"></a></div>