Search code examples
rplotdata-visualizationlattice

How can I get legend for coplot in r?


Using the iris dataset, I am going to find a way to get the legend in coplot when I define the color of point as variable variable, in this example (Species). in other words, I want to see a legend to tell me which shape and color represent which Species?

following is the script

coplot(Sepal.Width~Sepal.Length|Petal.Width*Petal.Length, data = iris,
number=c(3,3),overlap=.5,col=as.numeric(iris$Species),
pch=as.numeric(iris$Species)+1)

this is the produced graph: enter image description here


Solution

  • coplot(Sepal.Width~Sepal.Length|Petal.Width*Petal.Length, data = iris,
           number=c(3,3),overlap=.5,col=as.numeric(iris$Species),
           pch=as.numeric(iris$Species)+1)
    
    legend("topright", pch = unique(as.numeric(iris$Species)+1), 
           col = unique(as.numeric(iris$Species)), 
           legend = unique(iris$Species))
    

    You just have to adjust legend position to what fits better to your figure size.