armando
armando

Reputation: 1480

How to plot several columns of a matrix in the same plot in R?

I have a matrix called XY with the following entries:

0   1  1  3
2   4  2  3
4   2  3  5
6   2  5  6

I want to plot (in the same graph) columns 1 and 2 as the x and y axes respectively and columns 3 and 4 being the x and y axes respectively. I am trying the following code:

plot(XY[,1],XY[,2],type="l",col="red")
lines(XY[,3],XY[,4],col="green")
points(XY[,1],XY[,2],type="p",col="red")
points(XY[,3],XY[,4],type="p",col="green")

is there a more general way to do this graph without having to repeat the same code?

Thanks

Upvotes: 1

Views: 966

Answers (2)

linog
linog

Reputation: 6226

If you don't mind using ggplot rather than base plot (given the tags I think you don't), you can do:

library(ggplot2)

XY <- data.frame(XY)
colnames(XY)[1:4] <- c(paste0("var",1:4)) 
ggplot(data = XY) +
    geom_point(aes(x = var1, y = var2), color = "red") +
    geom_line(aes(x = var1, y = var2), color = "red") +
    geom_point(aes(x = var3, y = var4), color = "green") +
    geom_line(aes(x = var3, y = var4), color = "green")

The column name is a suggestion, maybe you have better variable names

Update

In order to have a legend, long formatted data are easier to handle. You can try something like that:

df <- rbind(
       cbind(XY[,c(1,2)], "group1"),
       cbind(XY[,c(3,4)], "group2")
      )
cols <- colnames(df)

Change "group1" and "group2" to relevent category names.

And you can plot like that:

ggplot(data = df, aes_string(x = cols[1], y = cols[2], col = cols[3])) +
    geom_point() +
    geom_line() +
    labs(color = "My colors")

I use aes_string because column names are quoted this time.

Upvotes: 1

Peter
Peter

Reputation: 12739

Try base R graphics matplot to avoid repeating code which both the base R and ggplot examples in their own different ways do.


matplot(XY[,c(1, 3)], XY[,c(2, 4)], type = "l", lty = 1, col = c("red", "green"), pch = 1,
        xlab = "X label", ylab = "Y label")
matpoints(XY[,c(1, 3)], XY[,c(2, 4)], type = "p", pch = 1, col = c("red", "green"))

This gives you:

enter image description here

Upvotes: 1

Related Questions