Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R lattice package: add legend to a figure

Tags:

r

legend

lattice

I am using the lattice package, and I want to add a legend to my figure. The documentation of auto.key and legend is very confusing, and couldn;t figure out the correct syntax to add a legend. Here is my code:

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)
       })

The graph is shown below, so I just want to add a legend for the lines. enter image description here

like image 788
Vahid Mirjalili Avatar asked Aug 03 '14 21:08

Vahid Mirjalili


1 Answers

I don't know exactly how you want this to look, but here is a start. In place of auto.key=T put:

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

This will put the key on the right side of the graph. You can use "top", "bottom", or "left" instead. If you want it inside the plot, get rid of space and instead use corner=c(0,1). The first number is location on the x-axis (from 0 to 1) the second for the y-axis. So this would put in in the upper left.

like image 124
John Paul Avatar answered Sep 22 '22 13:09

John Paul