12

I am using pairs(iris) to show possible relationships among the four variables (Sepal.length, Sepal.width, Petal.length, Petal.width) in the venerable Iris dataset.

When I add a color parameter...

pairs(iris[, 1:4], col = iris$Species)

...I can see the distinctions among the three species (Iris setosa, Iris virginica, and Iris versicolor), but the code -- as I've written it -- doesn't associate the colors with the species. In other words, there is no legend or anything that functions as a legend.

So someone suggested adding the following below that line of code...

par(xpd = TRUE)
legend( "bottomright", fill = unique(iris$Species), 
       legend = c( levels(iris$Species) ) )

...and although I get a legend box, the legend box overlays on the data in the pairs() graphic.

Is there a way to create something like a legend box for pairs() that does not overlap with the data presentation itself?

1 Answer 1

16

You can control the margin size with the oma argument to pairs. See the oma entry in ?par for details.

pairs(iris[, 1:4], col = iris$Species, oma=c(3,3,3,15))
par(xpd = TRUE)
legend("bottomright", fill = unique(iris$Species), legend = c( levels(iris$Species)))

enter image description here

1
  • For this to work with your data, note that Species if a factor. The column to color by must be changed to a factor for it to work.
    – TMWP
    Commented Aug 7, 2017 at 22:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.