R:具有多种颜色的图例框

时间:2015-06-23 13:32:48

标签: r plot legend

我有一个plot(),其中多个颜色阴影表示相同的事物。我想添加一个传奇,通过双色盒子传达这一点(见下面的例子)。有没有办法使用legend()或类似的命令来做到这一点?或者,有没有办法识别这些框的精确坐标,以便我可以在其上绘制一个多边形()三角形?

注意:legend()会返回外框的坐标和每个标签的左上角,但我不确定这是否足以计算彩色框的位置。

How it should look like

2 个答案:

答案 0 :(得分:1)

这有点像黑客,但你可以把两个传说放在另一个上面。不幸的是,没有左三角pch可能完全符合您的要求。

plot(1)
legend("bottomright",c("Label 1", "Label 2"),pch=22,col=c("red","blue"),pt.bg=c("red","blue"), pt.cex=1.8)
legend("bottomright",c("Label 1", "Label 2"),pch=21,col=c("green","orange"),pt.bg=c("green","orange"))

enter image description here

答案 1 :(得分:0)

稍微脏的黑客可以让你获得legend()功能来提供必要的信息。比我聪明的人可能会弄清楚legend()如何计算盒子定位并在函数外复制它。请注意,可能不建议编辑标准R函数。

如果您尚未编辑R功能,则可以通过简单(和临时)方式访问它,输入

fix(legend)

输入

rm(legend)

稍后会撤消您的更改。

找到显示fill <- rep的此部分,并添加评论所指示的行:

    fillList <- NULL ## added
    if (mfill) {
        if (plot) {
            fill <- rep(fill, length.out = n.leg)
            rect2(left = xt, top = yt + ybox/2, dx = xbox, dy = ybox, 
                col = fill, density = density, angle = angle, 
                border = border)
            fillList <- data.frame(left = xt, top = yt + ybox/2, dx = xbox, dy = ybox) ## added
        }
        xt <- xt + dx.fill
    }

找到最后一行并将其更改为

    invisible(list(rect = list(w = w, h = h, left = left, top = top), 
        text = list(x = xt, y = yt), fillList=fillList)) ## modified

现在通过

调用图例
output <- legend(...) ## replace ... with whatever you want to have as inputs

和绘制三角形使用legend()返回的信息,如下所示:

    with(output$fillList[1,], { ## first box
        polygon(c(left, left+dx, left+dx), c(top, top, top-dy), col=myColour, border=NA)
    })

Result