I am using some old code and it is not functioning as it used to. I just want to have a legend in R with lines and points overlapping, using base R. One used to be able to use pch=NA to have the symbols not appear in a first call to legend then make a subsequent call to legend with pch specified. The legends would overlap. But now it appears that R only accepts the last call to legend:
plot( 0, type="n", xlim=c(0,5), ylim=c(0,5) )
A <- matrix( c( c(1,2,3,4), c(2,1,2,4)), ncol=2 )
B <- matrix( c( c(1,2,3,4), c(1,3,3,2)), ncol=2 )
lines( A, col="red" )
points( A, col="blue", pch=15 )
lines( B, col="green" )
points( B, col="purple", pch=17 )
legend( x="topleft",
legend=c("Red line, blue points","Green line, purple points"),
col=c("red","green"), lwd=1, lty=c(1,2),
pch=c(NA,NA) )
legend( x="topleft",
legend=c("Red line, blue points","Green line, purple points"),
col=c("blue","purple"), lwd=1, lty=c(0,0),
pch=c(15,17) )
One can see that the legend should be lines and points, but because the points were called second, it is only the points that are given in the legend, not the lines.
Is there a new command for overlapping legends, or something like that? I can't see that anywhere.
This may be an issue with R 4.1.0 - as this plot worked in earlier versions.
Thank you!
I found the answer: you have to set the legend option 'bty="n"' (type of box to be drawn around the legend), for the second legend. Here is a working solution
plot( 0, type="n", xlim=c(0,5), ylim=c(0,5) )
A <- matrix( c( c(1,2,3,4), c(2,1,2,4)), ncol=2 )
B <- matrix( c( c(1,2,3,4), c(1,3,3,2)), ncol=2 )
lines( A, col="red" )
points( A, col="blue", pch=15 )
lines( B, col="green" )
points( B, col="purple", pch=17 )
legend( x="topleft",
legend=c("Red line, blue points","Green line, purple points"),
col=c("red","green"), lwd=1, lty=c(1,2),
pch=c(NA,NA) )
legend( x="topleft",
legend=c("Red line, blue points","Green line, purple points"),
col=c("blue","purple"), lwd=1, lty=c(0,0),
pch=c(15,17) ,bty="n")