Plot a legend outside of the plotting area in base graphics?

前端 未结 10 863
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 14:48

As the title says: How can I plot a legend outside the plotting area when using base graphics?

I thought about fiddling around with layout

10条回答
  •  旧巷少年郎
    2020-11-22 15:25

    Adding another simple alternative that is quite elegant in my opinion.

    Your plot:

    plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
    lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
    

    Legend:

    legend("bottomright", c("group A", "group B"), pch=c(1,2), lty=c(1,2),
           inset=c(0,1), xpd=TRUE, horiz=TRUE, bty="n"
           )
    

    Result:

    Here only the second line of the legend was added to your example. In turn:

    • inset=c(0,1) - moves the legend by fraction of plot region in (x,y) directions. In this case the legend is at "bottomright" position. It is moved by 0 plotting regions in x direction (so stays at "right") and by 1 plotting region in y direction (from bottom to top). And it so happens that it appears right above the plot.
    • xpd=TRUE - let's the legend appear outside of plotting region.
    • horiz=TRUE - instructs to produce a horizontal legend.
    • bty="n" - a style detail to get rid of legend bounding box.

    Same applies when adding legend to the side:

    par(mar=c(5,4,2,6))
    plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
    lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
    
    legend("topleft", c("group A", "group B"), pch=c(1,2), lty=c(1,2),
           inset=c(1,0), xpd=TRUE, bty="n"
           )
    

    Here we simply adjusted legend positions and added additional margin space to the right side of the plot. Result:

提交回复
热议问题