Iftikhar
Iftikhar

Reputation: 667

How to make multiple plots in r?

I have a large matrix mdat (1000 rows and 16 columns) contains first column as x variable and other columns as y variables. What I want to do is to make scatter plot in R having 15 figures on the same window. For example:

mdat <- matrix(c(1:50), nrow = 10, ncol=5)

In the above matrix, I have 10 rows and 5 columns. Is it possible that to use the first column as variable on x axes and other columns as variable on y axes, so that I have four different scatterplots on the same window? Keep in mind that I will not prefer par(mfrow=, because in that case I have to run each graph and then produce them on same window. What I need is a package so that I will give it just data and x, y varaibeles, and have graphs on same windows. Is there some package available that can do this? I cannot find one.

Upvotes: 0

Views: 3502

Answers (3)

Gregor Thomas
Gregor Thomas

Reputation: 145755

Perhaps the simplest base R way is mfrow (or mfcol)

par(mfrow = c(2, 2)) ## the window will have 2 rows and 2 columns of plots
for (i in 2:ncol(mdat)) plot(mdat[, 1], mdat[, i])

See ?par for everything you might want to know about further adjustments.

Another good option in base R is layout (the help has some nice examples). To be fancy and pretty, you could use the ggplot2 package, but you'll need to reshape your data into a long format.

require(ggplot2)
require(reshape2)
molten <- melt(as.data.frame(mdat), id = "V1")

ggplot(molten, aes(x = V1, y = value)) +
    facet_wrap(~ variable, nrow = 2) +
    geom_point()

Alternatively with colors instead of facets:

ggplot(molten, aes(x = V1, y = value, color = variable)) +
    geom_point()

Upvotes: 4

Martin Morgan
Martin Morgan

Reputation: 46856

Maybe

library(lattice)
x = mdat[,1]; y = mdat[,-1]
df = data.frame(X = x, Y = as.vector(y),
                Grp = factor(rep(seq_len(ncol(y)), each=length(x))))
xyplot(Y ~ X | Grp, df)

Upvotes: 2

Bryan Hanson
Bryan Hanson

Reputation: 6213

@user4299 You can re-write shujaa's ggplot command in this form, using qplot which means 'quick plot' which is easier when starting out. Then instead of faceting, use variable to drive the color. So first command produces the same output as shujaa's answer, then the second command gives you all the lines on one plot with different colors and a legend.

qplot(data = molten, x = V1, y = value, facets = . ~ variable, geom = "point")
qplot(data = molten, x = V1, y = value, color = variable, geom = "point")

Upvotes: 2

Related Questions