save multiple plots in R as a .jpg file, how?

假装没事ソ 提交于 2020-08-04 10:51:12

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/18584722/save-multiple-plots-in-r-as-a-jpg-file-how

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!