Antony Unwin
2019-Dec-01 15:48 UTC
[R] Adding a legend to a (multi-facet) plot produced by ggplot().
How about defining your dataset differently, making the colouring property a
variable?
xxx <- data.frame(x=rep(x, 4), y=c(y2, y3),
grp=factor(rep(c("a","b"),each=20, times=2)),
type=factor(rep(c("clyde", "irving"), each=40)))
ggplot(xxx, aes(x,y, colour=type, shape=type)) + geom_point() +
geom_abline(intercept=3, slope=2) + facet_wrap(vars(grp)) +
scale_colour_manual(values=c("blue", "red")) +
scale_shape_manual(values=c(20,3))
Then you could also plot the four groups separately if you wanted to:
ggplot(xxx, aes(x,y, colour=type, shape=type)) + geom_point() +
geom_abline(intercept=3, slope=2) + facet_grid(rows=vars(type), cols=vars(grp))
+ scale_colour_manual(values=c("blue", "red")) +
scale_shape_manual(values=c(20,3))
Antony Unwin
University of Augsburg,
Germany
> From: Rolf Turner <r.turner at auckland.ac.nz>
> Subject: [R] Adding a legend to a (multi-facet) plot produced by ggplot().
> Date: 1 December 2019 at 01:04:46 CET
> To: R help <R-help at r-project.org>
>
>
>
> I have been struggling to add a legend as indicated in the subject line,
> with no success at all. I find the help to be completely bewildering.
>
> I have attached the code of what I have tried in the context of a simple
> reproducible example.
>
> I have also attached a pdf file of a plot produced with base graphics to
illustrate roughly what I am after.
>
> I would be grateful if someone could point me in the right direction.
>
> cheers,
>
> Rolf Turner
>
> --
> Honorary Research Fellow
> Department of Statistics
> University of Auckland
> Phone: +64-9-373-7599 ext. 88276