<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/ggplot2-multiple-legends-for-the-same-aesthetic/"></div></div><div><a data-url="https://www.r-bloggers.com/ggplot2-multiple-legends-for-the-same-aesthetic/" data-counturl="https://www.r-bloggers.com/ggplot2-multiple-legends-for-the-same-aesthetic/" data-count="horizontal" data-text="ggplot2: multiple legends for the same aesthetic" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.quantide.com/ggplot-multiple-legends-for-the-same-aesthetic/"> R blog | Quantide - R training &amp; consulting</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Enrico is a colleague of mine in <a target="_blank" rel="nofollow" href="http://www.quantide.com/">Quantide</a>. Some days ago, he asked me how to get two different legends for several coloured lines.</p>
<p>This is the wanted result:</p>
<p><img sizes="(max-width: 500px) 100vw, 500px" alt="immagine-1" class="wp-image-3399" src="https://i0.wp.com/www.quantide.com/wp-content/uploads/2016/11/Immagine-1-2.png?resize=456%2C326" data-recalc-dims="1"></p>
<p>The first version of his plot sounds like the following one:</p>
<pre># Create a Dataframe with Random Data in order to reproduce examples
set.seed(456)
n &lt;- 20
dfr &lt;- data.frame(
  id=rep(1:n, 2),
  group=rep(c(&quot;1&quot;,&quot;2&quot;), each=n), value=c(rnorm(n), rnorm(n, sd=1.1))
)</pre>

<pre>require(ggplot2)

ggplot(data=dfr, mapping=aes(x=id, y=value)) +
  geom_line(mapping=aes(colour=group)) +
  geom_hline(yintercept=c(-1,1)*qnorm(0.95), color=&quot;orange&quot;) +
  geom_hline(yintercept=c(-1,1)*qnorm(0.99), color=&quot;darkred&quot;)</pre>
<p>
<img sizes="(max-width: 500px) 100vw, 500px" alt="immagine-2" class="wp-image-3400" src="https://i2.wp.com/www.quantide.com/wp-content/uploads/2016/11/Immagine-2-1-300x214.png?resize=456%2C326" data-recalc-dims="1">In this plot, he has six lines of four different colors:</p>
<ol>
<li>line of values for group 1 (red),</li>
<li>line of values for group 2 (lightblue),</li>
<li>horizontal lines for 95% limits (orange),</li>
<li>horizontal lines for 99% limits (dark red).</li>
</ol>
<p>When an aesthetic is mapped to data, the legend will be shown automatically. The plot shows the lines for group 1 and group 2.</p>
<p>To show the legend also for the horizontal lines, color of horizontal lines should be mapped to aesthetic.</p>
<p>Pay attention to horizontal lines positions, they have to be included in a data frame:</p>
<pre>df_95ci &lt;- data.frame(y_values=c(-1,1)*qnorm(0.95)) 
df_99ci &lt;- data.frame(y_values=c(-1,1)*qnorm(0.99))</pre>

<pre>ggplot(data=dfr, mapping=aes(x=id, y=value)) +
  geom_line(mapping=aes(colour=group)) +
  geom_hline(data= df_95ci, mapping=aes(yintercept=y_values, colour=&quot;A&quot;)) +
  geom_hline(data= df_99ci, mapping=aes(yintercept=y_values, colour=&quot;B&quot;))</pre>
<p>
<img sizes="(max-width: 500px) 100vw, 500px" alt="immagine-3" class="wp-image-3402" src="https://i1.wp.com/www.quantide.com/wp-content/uploads/2016/11/Immagine-3-1-300x214.png?resize=456%2C326" data-recalc-dims="1">Colours are mapped to “dummy” data. Since the values are shown in the legend, Enrico used labels as “dummy” data.</p>
<pre>ggplot(data=dfr, mapping=aes(x=id, y=value)) +
  geom_line(mapping=aes(colour=group)) +
  geom_hline(data= df_95ci, mapping=aes(yintercept=y_values, colour=&quot;95% CI&quot;)) +
  geom_hline(data= df_99ci, mapping=aes(yintercept=y_values, colour=&quot;99% CI&quot;))</pre>
<p>
<img sizes="(max-width: 500px) 100vw, 500px" alt="immagine-4" class="wp-image-3403" src="https://i0.wp.com/www.quantide.com/wp-content/uploads/2016/11/Immagine-4-300x214.png?resize=456%2C326" data-recalc-dims="1">To set colors for horizontal lines my colleague Enrico used <code>scale_color_manual()</code>. This function allows users to choose which colors should be used for each line.</p>
<pre>ggplot(data=dfr, mapping=aes(x=id, y=value)) +
  geom_line(mapping=aes(colour=group)) +
  geom_hline(data= df_95ci, mapping=aes(yintercept=y_values, colour=&quot;95% CI&quot;)) +
  geom_hline(data= df_99ci, mapping=aes(yintercept=y_values, colour=&quot;99% CI&quot;)) +
  scale_color_manual(values=c(&quot;black&quot;, &quot;blue&quot;, &quot;orange&quot;, &quot;darkred&quot;))</pre>
<p>
<img sizes="(max-width: 500px) 100vw, 500px" alt="immagine-5" class="wp-image-3404" src="https://i0.wp.com/www.quantide.com/wp-content/uploads/2016/11/Immagine-5-300x214.png?resize=456%2C326" data-recalc-dims="1">Enrico set four values for <code>scale_color_manual</code>: the first and second refers to the first colours mapped, that are the levels of group. The third value refers to the color Enrico called “95% CI”, the fourth value refers to the color Enrico called “99% CI”.</p>
<p>Of course, using <code>scale_color_manual()</code> information about default colors is lost so the colors for <code>group</code> should be declared. This can be annoying for (at least) two reasons: the number of groups may be not known and palettes are a better choice to get a set of colors. A work around consists of creating a function that rebuilds colors created by ggplot by default.</p>
<pre>gg_color_hue &lt;- function(n) {hcl(h=seq(15, 375, length=n+1), l=65, c=100)[1:n]}</pre>
<p>
The function is passed to the <code>value</code> argument of the <code>scale_color_manual()</code> function, replacing the color names such as “black” and “blue” in the above plot.</p>
<pre>ggplot(data=dfr, mapping=aes(x=id, y=value)) +
  geom_line(mapping=aes(colour=group)) +
  geom_hline(data= df_95ci, mapping=aes(yintercept=y_values, colour=&quot;95% CI&quot;)) +
  geom_hline(data= df_99ci, mapping=aes(yintercept=y_values, colour=&quot;99% CI&quot;)) +
  scale_color_manual(
  values=c(gg_color_hue(length(unique(dfr$group))), &quot;orange&quot;, &quot;darkred&quot;)
)</pre>
<p>
<img sizes="(max-width: 500px) 100vw, 500px" alt="immagine-6" class="wp-image-3405" src="https://i1.wp.com/www.quantide.com/wp-content/uploads/2016/11/Immagine-6-300x214.png?resize=456%2C326" data-recalc-dims="1">At this point, all works and Enrico was satisfied of its work. But the title of the legend, “group”, refers to the first two lines.</p>
<pre>ggplot(data=dfr, mapping=aes(x=id, y=value)) +
  geom_line(mapping=aes(colour=group)) +
  geom_hline(data= df_95ci, mapping=aes(yintercept=y_values, colour=&quot;95% CI&quot;)) +
  geom_hline(data= df_99ci, mapping=aes(yintercept=y_values, colour=&quot;99% CI&quot;)) +
  scale_color_manual(name= &quot;Legend&quot;, 
    values=c(gg_color_hue(length(unique(dfr$group))), &quot;orange&quot;, &quot;darkred&quot;))</pre>
<p>
<img sizes="(max-width: 500px) 100vw, 500px" alt="immagine-7" class="wp-image-3406" src="https://i1.wp.com/www.quantide.com/wp-content/uploads/2016/11/Immagine-7-300x214.png?resize=456%2C326" data-recalc-dims="1">The title of the legend can be easily changed, as it is the first argument of the <code>scale_color_manual()</code> function. But the best solution for his plot, was two different legends: one for <code>group</code> levels and one for the CI horizontal lines. So Enrico asked me if I know how to do this with ggplot. “Yes, of course” was my reply. “I already did it, in the past”. But this was not true. What I did, was the opposite: I merged several aesthetics in a single legend. Maybe I will write a post about this topic, too. I was pretty sure that ggplot doesn’t implement a solution to have two legends for the same aesthetic by default. This is not coherent with the grammar idea (the GG in ggplot stands for Grammar of Graphics) and the strong link between plot and data behind <code>ggplot2</code> package. At the same time, I was pretty sure that someone find a workaround to this issue and share its solution on the net. Maybe someone found a solution but she/he did not share this solution with us. I was astonished, the reply to my question was “you can’t do it” (see, for example <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/17642190/how-to-set-multiple-legends-for-the-same-aesthetic-in-ggplot2">http://stackoverflow.com/questions/17642190/how-to-set-multiple-legends-for-the-same-aesthetic-in-ggplot2</a>).</p>
<p>During my attempts to get two legends, I tried with two different aesthetics, adding an aesthetic not really useful like <code>size</code>:</p>
<pre>ggplot(data=dfr, mapping=aes(x=id, y=value)) +
  geom_line(mapping=aes(colour=group)) +
  geom_hline(data= df_95ci, mapping=aes(yintercept=y_values, size= &quot;95% CI&quot;), colour = &quot;orange&quot;) +
  geom_hline(data= df_99ci, mapping=aes(yintercept=y_values, size= &quot;99% CI&quot;), colour=&quot;darkred&quot;)</pre>

<pre>## Warning: Using size for a discrete variable is not advised.</pre>
<p>
<img sizes="(max-width: 500px) 100vw, 500px" alt="immagine-8" class="wp-image-3407" src="https://i2.wp.com/www.quantide.com/wp-content/uploads/2016/11/Immagine-8-300x214.png?resize=456%2C326" data-recalc-dims="1">I got two legends, but the legend about horizontal lines does not help to understand the plot, beacuse it does not show the right color of the lines. This is coherent with the goal of the legend, that is clarify what the <code>size</code> aesthetic means, but does not help my readers to understand which line refers to which confidence interval (95% or 99%).</p>
<p>Fortunately, <code>guide_legend()</code> allows to change some aesthetic, like the colour, to the elements of the legend.</p>
<pre>ggplot(data=dfr, mapping=aes(x=id, y=value)) +
  geom_line(mapping=aes(colour=group)) +
  geom_hline(data= df_95ci, mapping=aes(yintercept=y_values, size= &quot;95% CI&quot;), colour = &quot;orange&quot;) +
  geom_hline(data= df_99ci, mapping=aes(yintercept=y_values, size= &quot;99% CI&quot;), colour=&quot;darkred&quot;) +
  scale_size_manual(
    &quot;CI horizontal line&quot;, values=rep(1,4),
    guide=guide_legend(override.aes = list(colour=c(&quot;orange&quot;, &quot;darkred&quot;))))</pre>
<p>
<img sizes="(max-width: 500px) 100vw, 500px" alt="immagine-9" class="wp-image-3408" src="https://i2.wp.com/www.quantide.com/wp-content/uploads/2016/11/Immagine-9-300x214.png?resize=456%2C326" data-recalc-dims="1">This is what I was looking for: <strong>multiple legends for a single aesthetic</strong>. Finally, I only added the name for the legend of the <code>group</code> level, and all was done. As seen above, “hue” is the default scale for ggplot discrete colours. So the function, is <code>scale_color_hue()</code>.</p>
<pre>ggplot(data=dfr, mapping=aes(x=id, y=value)) +
  geom_line(mapping=aes(colour=group)) +
  geom_hline(data= df_95ci, mapping=aes(yintercept=y_values, size= &quot;95% CI&quot;), colour = &quot;orange&quot;) +
  geom_hline(data= df_99ci, mapping=aes(yintercept=y_values, size= &quot;99% CI&quot;), colour=&quot;darkred&quot;) +
  scale_color_hue(&quot;Group&quot;) +
  scale_size_manual(
    &quot;CI horizontal line&quot;, values=rep(1,4),
    guide=guide_legend(override.aes = list(colour=c(&quot;orange&quot;, &quot;darkred&quot;)))
)</pre>
<p>
<img sizes="(max-width: 500px) 100vw, 500px" alt="immagine-10" class="wp-image-3409" src="https://i2.wp.com/www.quantide.com/wp-content/uploads/2016/11/Immagine-10-300x214.png?resize=456%2C326" data-recalc-dims="1">That’s all folks!!! Just some notes:</p>
<ol>
<li>“Dummy” data are useful for this example, and so they are used also to set labels. By the way, labels for the legend can be set using the <code>labels</code> argument of the <code>scale_size_manual()</code>function (and, of course, of any other <code>scale_*_*</code> function).
<pre>ggplot(data=dfr, mapping=aes(x=id, y=value)) +
  geom_line(mapping=aes(colour=group)) +
  geom_hline(data= df_95ci, mapping=aes(yintercept=y_values, size= &quot;95% CI&quot;), colour = &quot;orange&quot;) +
  geom_hline(data= df_99ci, mapping=aes(yintercept=y_values, size= &quot;99% CI&quot;), colour=&quot;darkred&quot;) +
  scale_color_hue(&quot;Group&quot;) +
  scale_size_manual(&quot;CI horizontal line&quot;, values=rep(1,4),
guide=guide_legend(override.aes = list(colour=c(&quot;orange&quot;, &quot;darkred&quot;))),
labels=c(&quot;CI of 95%&quot;, &quot;CI of 99%&quot;))</pre>
<p><img sizes="(max-width: 500px) 100vw, 500px" alt="immagine-11" class="wp-image-3410" src="https://i0.wp.com/www.quantide.com/wp-content/uploads/2016/11/Immagine-11-300x214.png?resize=456%2C326" data-recalc-dims="1">
<li>As seen above, changing labels will change the order of the legends. To set the order, the <code>guide_legend()</code> function provides an <code>order</code> argument.
<pre>ggplot(data=dfr, mapping=aes(x=id, y=value)) +
  geom_line(mapping=aes(colour=group)) +
  geom_hline(data= df_95ci, mapping=aes(yintercept=y_values, size= &quot;95% CI&quot;), colour = &quot;orange&quot;) +
  geom_hline(data= df_99ci, mapping=aes(yintercept=y_values, size= &quot;99% CI&quot;), colour=&quot;darkred&quot;) +
  scale_color_hue(&quot;Group&quot;, guide=guide_legend(order=1)) +
  scale_size_manual(&quot;CI horizontal line&quot;, values=rep(1,4),
guide=guide_legend(override.aes = list(colour=c(&quot;orange&quot;, &quot;darkred&quot;),order=2)),
labels=c(&quot;CI of 95%&quot;, &quot;CI of 99%&quot;))</pre>
<p><img sizes="(max-width: 500px) 100vw, 500px" alt="immagine-12" class="wp-image-3411" src="https://i2.wp.com/www.quantide.com/wp-content/uploads/2016/11/Immagine-12-300x214.png?resize=456%2C326" data-recalc-dims="1">Article originally published on Nov 2015 on <a target="_blank" rel="nofollow" href="http://www.milanor.net/blog/multiple-legends-for-the-same-aesthetic-2/">MilanoR</a> and now modified by Veronica Giro to maintain compatibility with the latest version of <code>ggplot2</code>.

<p>The post <a target="_blank" rel="nofollow" href="http://www.quantide.com/ggplot-multiple-legends-for-the-same-aesthetic/">ggplot2: multiple legends for the same aesthetic</a> appeared first on <a target="_blank" rel="nofollow" href="http://www.quantide.com/">Quantide – R training &amp; consulting</a>.</p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/ggplot2-multiple-legends-for-the-same-aesthetic/"></div></div><div><a data-url="https://www.r-bloggers.com/ggplot2-multiple-legends-for-the-same-aesthetic/" data-counturl="https://www.r-bloggers.com/ggplot2-multiple-legends-for-the-same-aesthetic/" data-count="vertical" data-text="ggplot2: multiple legends for the same aesthetic" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.quantide.com/ggplot-multiple-legends-for-the-same-aesthetic/"> R blog | Quantide - R training &amp; consulting</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/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=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/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/KF0KdYudtE8"></a></div></ol>