R: legend with points and lines being different colors (for the same legend item)

萝らか妹 提交于 2019-12-02 17:39:48

You can do this with 2 calls to legend, the 1st time plots the lines, then the second call plots over the top with invisible lines, but plots the points in the desired colors:

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

or for the second call to legend you can do something like this (so you don't have 2 copies of the text on top of each other):

legend( x="topleft", 
        legend=c("",""),
        col=c("blue","purple"), lwd=1, lty=c(0,0), 
        pch=c(15,17), bty='n' )

Of course this only lines up properly working from the left. If you want the plot in one of the right corners then save the return value from the first call to legend and use it for placement in the second call.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!