r单个jpeg上的多个图形

时间:2013-06-24 15:04:23

标签: r graph jpeg

我遇到了以下问题,如果有人能给我一些意见,我将不胜感激。

我想将多个数字导出到单个jpeg文件中。我先创建一个图形点阵然后导出。我的主要问题是它适用于pdf而不是jpeg。有什么想法吗?

谢谢

#set the windows of the frames
par(mfcol=c(3,2))

#create the jpeg file
jpeg(filename=names(a1),".jpg",sep=""),
     quality=100,
     width=1024,
     height=768)

#plot 1
plot(a1,b1)
#plot 2
plot(a1,b2)
#plot 3
plot(a1,b3)

#plot 4
plot(a2, c1)
#plot 5
plot(a2, c2)
#plot 6
plot(a2, c3)

#dev.off shuts down the specified (by default the current) graphical device
#here it passes the picture to the file
dev.off()

2 个答案:

答案 0 :(得分:1)

目前尚不清楚是否需要在单个jpeg文件中存储多个1024x768图像 - 这没有意义 - 是否需要包含6个图的单个jpeg图像。

正如我所说,与PDF不同,JPEG不是多页面格式。因此,您可以将R导出为多个JPEG文件,但不能在一个JPEG中包含所有单独的图形。

R的设备允许在文件名中使用通配符,因此如果您希望将六个图表导出到文件foo001.jpegfoo002.jpegfoo00x.jpeg,那么您可以使用以下

jpeg(filename = "foo%03d.jpeg", ....)
.... # plotting commands here
dev.off()

如果您在没有通配符/占位符的情况下执行多个绘图会发生什么情况,请说明?jpeg中的文档:

If you plot more than one page on one of these devices and do not
include something like ‘%d’ for the sequence number in ‘file’, the
file will contain the last page plotted.

处理多个页面的设备,因为基础文件格式允许它可以在单个文件中采用多个图表,因为它是有意义的,例如pdf()postscript()。这些设备具有参数onefile,可用于指示是否需要单个文件中的多个绘图。

然而,par(mfcol=c(3,2))让我觉得你想要在同一设备区域中使用3x2的图表。这是允许的,但您需要在打开par()设备后拨打jpeg() ,而不是之前。如图所示,您的代码将活动设备拆分为3x2绘图区域,然后打开一个新设备,该设备选择默认参数,而不是您在调用jpeg()之前在设备上设置的参数。这说明如下:

> plot(1:10)
> dev.cur()
X11cairo 
       2 
> op <- par(mfrow = c(3,2))
> jpeg("~/foo.jpg")
> par("mfrow")
[1] 1 1
> dev.off()
X11cairo 
       2 
> par("mfrow")
[1] 3 2

因此你想要的东西可能是:

jpeg(filename=names(a1),".jpg",sep=""), quality=100,
     width=1024, height=768)
op <- par(mfcol=c(3,2))
#plot 1
plot(a1,b1)
#plot 2
plot(a1,b2)
#plot 3
plot(a1,b3)
#plot 4
plot(a2, c1)
#plot 5
plot(a2, c2)
#plot 6
plot(a2, c3)
par(op)
dev.off()

答案 1 :(得分:0)

更正后的代码

#data
a1<-seq(1,20,by=1) 
b1<-seq(31,50,by=1)
b2<-seq(51,70,by=1)
b3<-seq(71,90,by=1)

#create the jpeg file
jpeg(filename="a.jpg",
     quality=100,
     width=1024,
     height=768)

#set the create the frames
par(mfcol=c(3,1))

#plot the graphs
plot(a1,b1)
plot(a1,b2)
plot(a1,b3)


#par(op)

#dev.off shuts down the specified (by default the current) graphical device
#here it passes the picture to the file
dev.off()