获取 plot() 边界框的值

8
我正在生成许多图表,其中xlimylim的值是我基于每个图表计算的。我想把图例放在图表区域外(正好在实际图表周围的框上方),但我无法弄清楚如何获取图表区域周围的框的最大y值。
是否有一种方法可以做到这一点?我可以通过手动更改legend()的x和y值将图例移动到所需位置,但对于我创建的图形数量来说,这需要很长时间。
谢谢!
-JM

1
尝试查看?parusr参数。 - joran
你是否在使用 ggplot 来绘制图表?如果你能展示一些示例代码和图形,那么会更有助于理解你的需求。 - Andrie
3个回答

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)

输入图像描述


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)

1

par()函数的oma、omd和omi参数控制图形的边界和边距 - 可以使用par()$omd(等)进行查询,并使用par(oma=c())进行设置(如果需要),其中向量最多可以有4个值 - 请参见?par。


par("omd") 是检索命名参数的更标准的方式。 - Gavin Simpson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接