[R] Adding a legend to a (multi-facet) plot produced by ggplot().

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Mon Dec 2 05:08:02 CET 2019


Hello,

Here are two ways of drawing the lines black and at the same time 
removing the lines in the legend. The second way is more idiomatic.


1. Override the colour setting in the ggplot call when drawing the lines:

geom_line(aes(y = y1), colour = "black") +


2. Don't set the colour aesthetic in the initial ggplot call. It will be 
needed only to draw the points, so set it in geom_point(). Though it 
doesn't influence the lines' colour and the lines in the legend, the 
same principle applies to shape = variable so I have moved it to 
geom_point().

The complete instruction becomes:


ggplot(long, aes(x, y = value)) +
   geom_line(aes(y = y1)) +
   geom_point(aes(colour = variable, shape = variable)) +
   scale_colour_manual("Doesn't work",values=c("blue","red"),
                       labels=c("clyde","irving")) +
   scale_shape_manual("Doesn't work",values=c(16,3),
                      labels=c("clyde","irving")) +

   facet_grid(cols=vars(grp))



Hope this helps,

Rui Barradas


Às 01:07 de 02/12/19, Rolf Turner escreveu:
> 
> On 2/12/19 3:03 am, Rui Barradas wrote:
> 
>> Hello,
>>
>> See if this is it. The standard trick is to reshape the data from wide 
>> to long, see the SO post [1]. Then add a scale_shape_* layer to the plot.
>>
>>
>> yyy <- cbind(xxx, y3 = y3)
>> long <- reshape2::melt(yyy, id.vars = c("x", "y1", "grp"))
>>
>> ggplot(long, aes(x, y = value, colour = variable, shape = variable)) +
>>    geom_line(aes(y = y1)) +
>>    geom_point() +
>>    scale_colour_manual("Doesn't work",values=c("blue","red"),
>>                        labels=c("clyde","irving")) +
>>    scale_shape_manual("Doesn't work",values=c(16,3),
>>                        labels=c("clyde","irving")) +
>>
>>    facet_grid(cols=vars(grp))
>>
>>
>> [1] 
>> https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format 
>>
>>
>> Hope this helps,
> 
> Almost there.  However the colour of the line changes with "values" and 
> lines show up in the legend.  I want the lines to be black in all 
> facets, and only points to show up in the legend.
> 
> I fiddled about a bit trying to achieve this but only succeeded in 
> messing things up completely.
> 
> Can you guide me a bit further, please?
> 
> cheers,
> 
> Rolf
>



More information about the R-help mailing list