添加另一个简单的选择,在我看来是相当优雅的。
你的阴谋:
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("bottomright", c("group A", "group B"), pch=c(1,2), lty=c(1,2),
inset=c(0,1), xpd=TRUE, horiz=TRUE, bty="n"
)
结果:
这里只向示例添加了图例的第二行。反过来:
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.
同样适用于在侧面添加图例:
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"
)
在这里,我们简单地调整了图例位置,并在图的右侧添加了额外的空白空间。结果: