R base plot legends 互相覆盖

R base plot legends writing over each other

我使用的是一些旧代码,但它无法像以前那样运行。我只想在 R 中使用线和点重叠的图例,使用基数 R。曾经可以使用 pch=NA 让符号不出现在第一次调用图例中,然后使用 pch 调用图例指定的。传说会重叠。但是现在看来R只接受最后一次调用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) )

看得出来图例应该是线和点,但是因为点是其次,所以图例中只给出了点,没有给出线

是否有重叠图例的新命令,或类似的命令?我在任何地方都看不到。

这可能是 R 4.1.0 的问题 - 因为该图在早期版本中有效。

谢谢!

我找到了答案:您必须为第二个图例设置图例选项 'bty="n"'(要在图例周围绘制的框类型)。这是一个可行的解决方案

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")