Note that there are some explanatory texts on larger screens.

plurals
  1. POLegend with subgroups in ggplot2
    primarykey
    data
    text
    <p>I want to plot the following dataset:</p> <pre><code>data&lt;-list() data$Year&lt;-c(rep(1995,4),rep(2005,4)) data$Name&lt;-as.factor(c("name1","name2","name3","name4","name1","name2","name3","name4")) data$species&lt;-as.factor(c("cat","cat","dog","dog","cat","cat","dog","dog")) data$Value&lt;-c(1,2,3,4,5,6,7,8) data&lt;-as.data.frame(data) </code></pre> <p>This is my desired plot</p> <pre><code>p&lt;-ggplot(data, aes(x=Year, y=Value,fill=Name, colour=Name,linetype=species,shape=species)) p&lt;-p+geom_point() p&lt;-p+geom_line() </code></pre> <p>I want a different legend however. First, the legend should contain one entry for each 'name' with the correct symbol(color, linetype and shape). I can achieve this by doing the following (the linetypes do not exactly match, sorry):</p> <pre><code>#Plot with better legend gg_color_hue &lt;- function(n) { hues = seq(15, 375, length=n+1) hcl(h=hues, l=65, c=100)[1:n] } p2&lt;-ggplot(data, aes(x=Year, y=Value,fill=Name, colour=Name,linetype=Name,shape=Name)) p2&lt;-p2+scale_linetype_manual(values=c(1,1,2,2),breaks=levels(data$Name),name="test") p2&lt;-p2+scale_shape_manual(values=c(16,16,17,17),breaks=levels(data$Name),name="test") p2&lt;-p2+scale_colour_manual(values=gg_color_hue(4),breaks=levels(data$Name),name="test") p2&lt;-p2+scale_fill_manual(values=gg_color_hue(4),breaks=levels(data$Name),name="test") p2&lt;-p2+geom_point(show_guide=T) p2&lt;-p2+geom_line(show_guide=T) </code></pre> <p>Now however there is no distinction between cats and dogs anymore. Therefore I would like to have subtitles in the legend (or essentially two legends): Something like this:</p> <pre><code>cats symbol(name1) name1 symbol(name2) name2 dogs symbol(name3) name3 symbol(name4) name4 </code></pre> <p>Can somebody help me on this? Thank you.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload