Peng Yu
2009-Oct-18 20:37 UTC
[R] How to plot multiple data sets with different colors (also with legend)?
The following commands only show the data in 'y'. I'm wondering how to show the data in 'x' as well. I also want to add a legend to show that blue points corresponds to 'x' and yellow points correspond to 'y'. Could somebody let me know what the correct commands should be? x=rbind(c(10,11),c(10,11)) y=cbind(-1:0,-1:0) plot(y,col='yellow') points(x,col='blue')
Matthieu Dubois
2009-Oct-18 22:42 UTC
[R] How to plot multiple data sets with different colors (also with legend)?
Hi, the blue point is not shown simply because it is printed outside the current plot area. If you want to use the base graphics, you have to manually define the xlim and ylim of the plot. Legend is added with the command "legend". E.g. x=rbind(c(10,11),c(10,11)) y=cbind(-1:0,-1:0) plot(y,col='yellow', xlim=c(-1,11), ylim=c(-1,11)) points(x,col='blue') legend("topleft", c("x","y"), col=c('blue', 'yellow'), pch=1) This is nevertheless most easily done in ggplot2. E.g. library(ggplot2) # put the whole data in a data frame # and add a new variable to distinguish both dat <- data.frame(rbind(x,y), var=rep(c('x','y'), each=2)) qplot(x=X1,y=X2, colour=var, data=dat) HTH, Matthieu
Jim Lemon
2009-Oct-18 23:02 UTC
[R] How to plot multiple data sets with different colors (also with legend)?
On 10/19/2009 07:37 AM, Peng Yu wrote:> The following commands only show the data in 'y'. I'm wondering how to > show the data in 'x' as well. I also want to add a legend to show that > blue points corresponds to 'x' and yellow points correspond to 'y'. > Could somebody let me know what the correct commands should be? > > x=rbind(c(10,11),c(10,11)) > y=cbind(-1:0,-1:0) > plot(y,col='yellow') > points(x,col='blue') > >Hi Peng, To show the "x" points, you will have to set both the xlim and ylim arguments: plot(y,col="yellow",xlim=c(-1,11),ylim=c(-1,11)) points(x,col="blue") I'm not sure why you are passing the points as matrices, but this means that the "x" points are the same. Jim