绘制并保存R图

时间:2012-06-13 17:29:20

标签: r bash

我有一个bash脚本,可以在运行命令时跟踪内存使用情况。它产生所需的命令,然后写入一个日志,其中column1 =“memory by program(gigs)”,第2列是到目前为止经过的时间,以秒为单位。 e.g。

31.282 1470
31.565 1480
31.848 1490
31.989 1500
32.273 1510
32.414 1520
32.697 1530
32.980 1540
33.122 1550
33.405 1560
6.511 1570
6.935 1580
7.502 1590
7.926 1600
8.351 1610
8.775 1620
9.059 1630
9.483 1640
9.908 1650
10.333 1660

我想要做的是等到过程完成后再使用R绘制一段时间内存使用情况的图表并将其保存在当前目录中。我正在玩R,我确切地知道我需要使用哪些命令:

> heisenberg <- read.csv(file="4644.log",head=FALSE,sep=" ")
> plot(heisenberg$V2,heisenberg$V1,type="o",col="red",main="Memory Usage Over Time",xlab="Time (seconds)",ylab="Memory (gigabytes)")
> text(max(heisenberg$V2),max(heisenberg$V1),max(heisenberg$V1)) #Displays max value

但我坚持的部分是将图表保存为jpg或png。或者我如何在我的bash脚本中执行此命令。我是否绝对需要用R语言编写另一个脚本并运行它?这可以做到一次吗?


修改

这是我的script.r

的代码
png("mem_usage_2965.png",height=800,width=800)
heisenberg <- read.csv(file="2965.log",head=FALSE,sep=" ")
plot(heisenberg$V2,heisenberg$V1,type="o",col="red",main="oases_k85",xlab="Time (seconds)",ylab="Memory (gigabytes)")
text(max(heisenberg),max(heisenberg),max(heisenberg))
dev.off()

任何人都可以帮忙解释为什么文本不会输出输出的png中的最大值?我在像R CMD BATCH script.r script.out

这样的bash脚本中调用它

2 个答案:

答案 0 :(得分:13)

将你的情节电话打包:

jpeg("myplot.jpg")
....plot code here....
dev.off()

png("myplot.png")
....plot code here....
dev.off()

有关其他参数的详细信息,请参阅各自的帮助页面:?png

对于PNG,这将是:

png("my_plot.png", height = 800, width = 600)
plot(heisenberg$V2,heisenberg$V1,type="o",col="red",main="Memory Usage Over Time",xlab="Time (seconds)",ylab="Memory (gigabytes)")
text(max(heisenberg$V2),max(heisenberg$V1),max(heisenberg$V1)) #Displays max value
dev.off()

至于在bash脚本中运行它,你需要调用R来运行包含R代码的脚本来加载数据并绘制图。为此,有几个选项,其中两个是:

R CMD BATCH --no-save --no-restore my_script.R

或使用Rscript

Rscript my_script.R

其中my_script.R是一个文本文件,包含生成图表所需的语法上有效的R代码。

答案 1 :(得分:2)

你只是在看简单吗? http://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/png.html

你基本上告诉R开始使用以下命令保存.png:

png(file="blah.png")

然后使用:

dev.off()

恢复正常。