1

I am making a scatterplot matrix with three variables (x,y,z) with the points coloured different based on type (w). I want to add a legend to this scatterplot matrix to explain what the colours of plotted points stand for. However, the legend command does not seem to work (i.e. I see no legend in the plot), and trying to change margins of the scatterplot matrix seems to not be working either (no change seems to happen in the plot). My code is as below:

 x <- rnorm(20, 1, 0.1) 
 y <- rnorm(20, 5, 1) 
 z <- rnorm(20, 10, 2) 
 w <- c(1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2) 
 dat <- data.frame(x, y, z, w) 

 pallet = c( "red", "blue") 

 plot(dat[c('x','y','z')], col=pallet[dat$w]) 
 legend("topright", legend=c("one", "two"), col=pallet)

Is there a way to add a legend to a scatterplot matrix that I am missing here?

  • Can you please include data and/or code that will provide us with a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) ? – Ben Bolker Sep 20 '16 at 18:57
  • Thanks @user20650. Not good at stackoverflow yet. – Ayesha Shahid Sep 20 '16 at 19:18
  • from http://stackoverflow.com/questions/14948852/how-to-use-the-pairs-function-combined-with-layout-in-r , this seems to work `plot(dat[c('x','y','z')], col=pallet[dat$w], oma = c(5, 4, 4, 10)) ; legend("topright" , legend=c("one", "two"), fill=pallet, xpd=TRUE)` – user20650 Sep 20 '16 at 19:31
  • That seems to work some times. For some reason, the first time I run the code, the legend pops up. But if I run it again (for example to move around the location of the legend), the legend does not show until I restart R and run the code afresh. Can you think of why this may be happening. – Ayesha Shahid Sep 20 '16 at 20:39
  • It will depend on what parameter value you set the outer margin (oma) too, and the corresponding position you put the legend. (In the example above, as the legend is positioned at the topright, then extra space is added to the right of the plot (position four)). It will also depend a bit on the size of the graphics window. – user20650 Sep 20 '16 at 21:10
  • I thought thats what it was but I am not changing the code, just running the same code again. The first time the legend shows up and the second time it doesn't. It seems this is a problem with R and if I use the command dev.off() to clear off my plot, that fixes that. – Ayesha Shahid Sep 20 '16 at 21:29

0 Answers0