传说在 R 情节的背后

Legend goes behind the lines in R plot

我正在使用以下示例代码生成绘图

x=seq(1,10, length=100)       
y=seq(-5,5,length=100)    
pdf("plot.pdf")   
plot(y~x, type="n", xlab="", ylab="")     
for(i in 1:4){   
y=rnorm(100, mean=i, sd=i)   
lines(x,y, type="l",lty=i)     
}   
legend("topright", legend=c("a", "b", "c"), lty=c(1,2,3,4), pch=c(1,2,3,4))   
dev.off()   

当我以 pdf 格式保存绘图时,图例位于绘制的线条后面。虽然我希望图表在以 pdf 格式保存时看起来应该如下所示。

如您所见,图例的背景颜色默认为 "transparent"。要将其设置为不透明 "white",请使用其 bg 参数,如下所示:

legend("topright", legend=c("a", "b", "c"), lty=c(1,2,3,4), pch=c(1,2,3,4),
       bg = "white")

它不在顶部,它是透明的。在图例命令中设置参数 bg = 'white'