Warm tip: This article is reproduced from stackoverflow.com, please click
r

How can I integrate the "Export --> Save as Image" Click Process into a script?

发布于 2020-03-29 12:46:19

I have a script that defines 4 variables and finally yields a graphic representation of them. Each time I run the script, the representation is different.

I would like to add a line of code so that each representation is saved as a png file (or jpg) and will not be overwritten by the next image from the following iteration.

Thanks for any advice.

Code:

f1=jitter(sample(c(2,3),1));
f2=jitter(sample(c(2,3),1));
f3=jitter(sample(c(2,3),1));
f4=jitter(sample(c(2,3),1));
d1=runif(1,0,1e-02);
d2=runif(1,0,1e-02);
d3=runif(1,0,1e-02);
d4=runif(1,0,1e-02)
p1=runif(1,0,pi);
p2=runif(1,0,pi);
p3=runif(1,0,pi);
p4=runif(1,0,pi);
xt = function(t) exp(-d1*t)*sin(t*f1+p1)+exp(-d2*t)*sin(t*f2+p2)
yt = function(t) exp(-d3*t)*sin(t*f3+p3)+exp(-d4*t)*sin(t*f4+p4)
t=seq(1, 100, by=0.001)

dat=data.frame(t=t, x=xt(t), y=yt(t)) 
with(dat, plot(x,y, type="l", xlim =c(-2,2), ylim =c(-2,2), xlab = "", ylab = "", xaxt='n', yaxt='n'))
Questioner
TomTe
Viewed
16
Gowachin 2020-01-31 16:29

Here is an attempt to answer your question. I tested your code and at least it works on Ubuntu 18.04.

# your code up

# create the file
png(filename = "test.png", width = 480, height = 480, units = "px", pointsize = 12, bg = "white", res = NA, type = c("cairo", "cairo-png", "Xlib", "quartz"))
# plot
with(dat, plot(x,y, type="l", xlim =c(-2,2), ylim =c(-2,2), xlab = "", ylab = "", xaxt='n', yaxt='n'))
# close the file
dev.off()