[R] A custom legend for three data frames in one plot
Jim Lemon
jim at bitwrit.com.au
Mon Jul 7 03:28:54 CEST 2014
On Sun, 6 Jul 2014 05:31:34 PM Artur Rataj wrote:
> Hello. I have three data frames, and made a single plot out of them.
Here
> is a workable example:
>
> cloud2 <- data.frame(x = c(0, 1, 2), y = c(0.3, 0.4, 0.5))
> sandwich3 <- data.frame(x = c(1, 2, 3), y = c(0.4, 0.5, 0.6), p =
> c(0.1, 0.6, 0.3))
> sandwich4 <- data.frame(x = c(3, 4, 5), y = c(0.6, 0.3, 0.5), p =
> c(0.1, 0.7, 0.2))
> ggplot(cloud2, aes(x=x, y=y)) +
geom_line(size=0.1,colour="gray70") +
> aes(x=x, y=y, size=sqrt(p)) +
> geom_point(data=sandwich3,colour="gray40",shape=15) +
> scale_size(range=c(0,2)) +
> geom_point(data=sandwich4,colour="black",shape=16) +
> theme(legend.position=c(0.905, 0.14),
legend.title=element_blank(),
> axis.ticks = element_line(colour = "black"), axis.text =
> element_text(colour = "black")) +
> scale_x_continuous(limits = c(-5, 5), breaks=c(-2, 0, 2)) +
> scale_y_continuous(limits = c(-1.1, 1.2))
>
> The problem is, that the default legend ignores two of the data
frames, and
> needlessly draws size levels for the third data frame. I would want a
> legend like that instead:
>
> [light gray line] graph 1
> [black circle of size=1] graph 2
> [gray rectangle of size=1] graph 3
>
> I tried scale_colour_manual, guide=legend, etc., but it changes
nothing.
> How could it be done?
> Cheers,
> Artur
>
Hi Artur,
Here is one way.
plot(cloud2,type="l",col="lightgray",xlim=c(0,5),ylim=c(0.3,0.6))
points(sandwich3)
points(sandwich4,pch=5,col="gray")
legend(3,0.5,c("cloud2","sandwich3","sandwich4"),
lty=c(1,NA,NA),pch=c(NA,1,5),col=c("lightgray","black","gray"))
Jim
More information about the R-help
mailing list