R中的lattice包:向图形添加图例

13

我正在使用lattice包,想要在我的图形中添加一个图例。但是auto.keylegend的文档非常混乱,我无法找出正确的语法来添加图例。这是我的代码:

xyplot(y ~ x, df, pch=19, col=rgb(0.2, 0.4, 0.8, 0.7), cex=2,
       scales=list(cex=1.7),
       xlab=list("x", cex=1.ales=list(cex=1.7),
       xlab=list("x", cex=1.7), ylab=list("y", cex=1.7),
       main=list("Linear Regression w. Polynomial Attributes", cex=1.6),
       auto.key=T,
       panel = function(x, y, ...) {
            panel.xyplot(x, y, ...)
            llines(x, predict(lm.xtend), col="purple", lwd=6, lty=3)
            llines(x, predict(ridge.lin), col="darkgreen", lwd=6, lty=2)
       })

下图显示了数据曲线,我只想为这些曲线添加图例。 enter image description here

1
legend 函数不属于 grid/lattice/ggplot 绘图系统。您正在尝试混合使用基础绘图和网格绘图。在 lattice 中,它需要是 legend=list('inside' = someGrobMakingFunction)。您应该学习使用 key=list...) 机制。 - IRTFM
仍然没有示例,因此不清楚您希望看到什么。在xyplot调用中没有组或条件变量,因此不清楚应该如何构建具有两个文本值的图例。也许您只想添加一个文本框? - IRTFM
1个回答

22

我不知道你想要的具体效果是什么,但这里有一个开始。在 auto.key=T 的位置上,替换为:

key=list(space="right",
         lines=list(col=c("purple","darkgreen"), lty=c(3,2), lwd=6),
         text=list(c("Purple Line"," Dark-green Line"))
)

这将把关键字放在图形的右侧。您可以使用“top”,“bottom”或“left”代替。如果您想将其放在图中,请删除space并改用corner=c(0,1)。第一个数字是x轴上的位置(从0到1),第二个数字是y轴上的位置。因此,这将放在左上角。


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