获取plot()边界框值

时间:2011-09-06 15:24:47

标签: r

我正在生成多个包含xlimylim值的图,我在每个图的基础上进行计算。我想把我的传说放在情节区域之外(就在实际情节周围的方框上方),但我无法弄清楚如何在我的情节区域周围获得框的最大y值。

有没有办法做到这一点?我可以通过手动更改legend() x和y值来将图例移动到我想要的位置,但这需要很长时间才能创建我正在创建的图表数量。

谢谢!

-JM

3 个答案:

答案 0 :(得分:13)

以下是使用?legend中的一个代码示例说明我认为您正在寻找的内容的基本示例。

#Construct some data and start the plot
x <- 0:64/64
y <- sin(3*pi*x)
plot(x, y, type="l", col="blue")
points(x, y, pch=21, bg="white")

#Grab the plotting region dimensions
rng <- par("usr")

#Call your legend with plot = FALSE to get its dimensions
lg <- legend(rng[1],rng[2], "sin(c x)", pch=21, 
            pt.bg="white", lty=1, col = "blue",plot = FALSE)

#Once you have the dimensions in lg, use them to adjust
# the legend position
#Note the use of xpd = NA to allow plotting outside plotting region             
legend(rng[1],rng[4] + lg$rect$h, "sin(c x)", pch=21, 
            pt.bg="white", lty=1, col = "blue",plot = TRUE, xpd = NA)

enter image description here

答案 1 :(得分:3)

命令par('usr')将返回边界框的坐标,但您也可以使用grconvertXgrconvertY函数。一个简单的例子:

plot(1:10)
par(xpd=NA)
legend(par('usr')[1], par('usr')[4], yjust=0, legend='anything', pch=1)
legend( grconvertX(1, from='npc'), grconvertY(1, from='npc'), yjust=0,
 xjust=1, legend='something', lty=1)

答案 2 :(得分:1)

par()控制边界和图边距的oma,omd和omi参数 - 可以使用par()$omd(等)查询它们。并使用par(oma=c())设置(如果需要)(其中向量最多可以包含4个值 - 请参阅?par)