10

I am very new to R and I am using it for my probability class. I searched for this question here, but it looks that is not the same as I want to do. (If there is already an answer, please tell me).

The problem is that I want to save multiple plots of histograms in the same file. For example, if I do this in the R prompt, I get what I want:

library(PASWR)
data(Grades)
attach(Grades) # Grade has gpa and sat variables
par(mfrow=c(2,1))
hist(gpa)
hist(sat)

So I get both histograms in the same plot. but if I want to save it as a jpeg:

library(PASWR)
data(Grades)
attach(Grades) # Grades has gpa and sat variables

par(mfrow=c(2,1))
jpeg("hist_gpa_sat.jpg")
hist(gpa)
hist(sat)
dev.off()

It saves the file but just with one plot... Why? How I can fix this? Thanks.

Also, if there is some good article or tutorial about how to plot with gplot and related stuff it will be appreciated, thanks.

Edwardo
  • 643
  • 3
  • 9
  • 23

2 Answers2

16

Swap the order of these two lines:

par(mfrow=c(2,1))
jpeg("hist_gpa_sat.jpg")

so that you have:

jpeg("hist_gpa_sat.jpg")
  par(mfrow=c(2,1))
  hist(gpa)
  hist(sat)
dev.off()

That way you are opening the jpeg device before doing anything related to plotting.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
1

You could also have a look at the function layout. With this, you can arrange plots more freely. This example gives you a 2 column layout of plots with 3 rows.

The first row is occupied by one plot, the second row by 2 plots and the third row again by one plot. This can come in very handy.

x <- rnorm(1000)
jpeg("normdist.jpg")
layout(mat=matrix(c(1,1,2,3,4,4),nrow=3,ncol=2,byrow=T))
boxplot(x, horizontal=T)
hist(x)
plot(density(x))
plot(x)
dev.off()

Check ?layout how the matrix 'mat' (layout's first argument) is interpreted.

swolf
  • 1,020
  • 7
  • 20