首页 文章

自动计算图例的适当插入值

提问于
浏览
6

是否可以自动获得 inset 的适当值,以便图例的左角始终位于图的右上角之外?

在下面的图中,我必须手动为 inset 尝试几个值 . 不必手动操作会很好,因为我必须制作多个图 .

graphics.off()
windows(width = 5, height = 5)
set.seed(42)
par(mar = c(5,5,1,10))
plot(rnorm(50,15,5), rnorm(50,15,3),
                xlim = c(0,30), ylim = c(5,25),
                pch = 19, col = c("red","blue"))

par(xpd = TRUE)
legend("topright", inset = c(-.80, 0),
                pch = 19, col = c("red","blue"),
                legend = c("LEGEND 1","Second Legend"))

enter image description here

1 回答

  • 5

    plot 调用之后,在添加 legend 之前,使用 par("usr") *来提取绘图区域的坐标 .

    然后,不使用'keyword'和 inset 定位图例,而是使用 xy 以及从 par("usr") 获得的绘图区域的右上角坐标 . 使用合适的系数调整 x .

    coord <- par("usr")
    legend(x = coord[2] * 1.05, y = coord[4],
           pch = 19, col = c("red", "blue"),
           legend = c("LEGEND 1", "Second Legend"))
    

    enter image description here


    而且只是为了好玩,一个更复杂的选择 .

    plot ting之后,使用位置 topright 调用 legend ,但不将其绘制到设备( plot = FALSE ),并将其分配给对象 .

    提取图例框的左 x 和顶部 y 坐标及其宽度(请参阅 ?legend 中的值部分),以便在 x 中使用 y 中的 y

    leg <- legend("topright", pch = 19, col = c("red", "blue"),
                  legend = c("LEGEND 1", "Second Legend"),
                  plot = FALSE)
    
    legend(x = (leg$rect$left + leg$rect$w) * 1.05, y = leg$rect$top,
           pch = 19, col = c("red", "blue"),
           legend = c("LEGEND 1", "Second Legend"))
    

    enter image description here


    *从 ?par

    usr形式为c(x1,x2,y1,y2)的向量,给出绘图区域的用户坐标的极值 .

    指定 inset 参数时进行的位置计算实际上基于 par("usr") (参见legend code中的第188-199行) .

相关问题