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

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'))

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()

Related

How to open an image?

enter image description here
I use 'openImage' package to import multiple images,
#this sets the directory
list\<- list.files("C://Users//Bilal//Desktop//test//bb", all.files
= FALSE,full.names = TRUE)
#this loop to import the images
df<-data.frame()
#df <-list()
for (i in seq_along(lista)) {
pic<-readImage(lista[i])
pic<-rgb_2gray(pic)
pic<-resizeImage(pic, width = 48, height = 64)
pic<-as.vector(pic)
pre_pic<-t(pic)
df<-rbind(df,pre_pic)}
#this code is used to open the image but the second line does not work
#Error in image.default(df, xaxt = "n", yaxt = "n", col = grayscale) :
#'z' must be a matrix
grayscale <- gray(seq(0, 1, length = 100))
image(df[,,1], xaxt='n', yaxt='n', col=grayscale)
This is what I expect to see
I understand now what's happening; thanks for sharing the image. First- you were/are using grDevices::image() <- the base R function.
The error tells you that R can't determine how you shaped your data. When you flattened the matrix into a vector, you knew it was 48 x 64, but that information wasn't there when you sent it to image.
You could do either one of the following:
# before making it a vector
image(t(p3), col = grayscale, yaxt = 'n', xaxt = 'n')
# after making it a row in a data frame
image(t(matrix(unlist(df[1,]), ncol = 64, nrow = 48)),
col = grayscale, yaxt = 'n', xaxt = 'n')

How can I fit two semivariograms in one plot in R?

I tried to plot two semivariogram in one plot but unfortunately it does not work.
I guess the solution is pretty easy but I am at the end of my latin.
This ist the code of the variograms I want to put in one plot together:
variog_iso_a1 <- fit.variogram( emp_variog_iso_a1,
vgm( psill = 2000,
model = "Sph",
range = 200,
nugget = 500))
plot(emp_variog_iso_a1, variog_iso_a1, as.table=TRUE, main = "Acker H1 C_org", plot.numbers=T)
variog_iso_a2 <- fit.variogram( emp_variog_iso_a2,
vgm( psill = 2000,
model = "Sph",
range = 200,
nugget = 500))
plot(emp_variog_iso_a2, variog_iso_a2, as.table=TRUE, main = "Acker H2 C_org", plot.numbers=T)
Secondly I would also like to plot two semivariogram in one plot but with a second y-axis on the right side because of the different values.
variog_iso_a1 <- fit.variogram( emp_variog_iso_a1,
vgm( psill = 2000,
model = "Sph",
range = 200,
nugget = 500))
plot(emp_variog_iso_a1, variog_iso_a1, as.table=TRUE, main = "Acker H1 C_org", plot.numbers=T)
variog_iso_l1 <- fit.variogram( emp_variog_iso_l1,
vgm( psill = 2000,
model = "Sph",
range = 200,
nugget = 500))
plot(emp_variog_iso_l1, variog_iso_l1, as.table=TRUE, main = "Acker H1 Lichtwert", plot.numbers=T)
I was only able two show the points of each variogram but not with the model fitted inside. This is the code I tried but does not work!
plot(emp_variog_iso_a1$dist, emp_variog_iso_a1$gamma, ylim=c(0,2500))
points(emp_variog_iso_a2$dist, emp_variog_iso_a2$gamma, col = "red", add=T, labels=emp_variog_iso_a2$np)
plot(emp_variog_iso_a1$dist, emp_variog_iso_a1$gamma, ylim=c(0,2500),main="Semivarianz Lichtwert und organische Substanz Horizont 1 Ackerland", ylab = "Semivarianz", xlab = "Distanz" )
par(new = TRUE)
plot(emp_variog_iso_l1$dist, emp_variog_iso_l1$gamma, col = "red", labels=emp_variog_iso_l1$np )
points(emp_variog_iso_l1$dist, emp_variog_iso_l1$gamma, col = "red", add=T, labels=emp_variog_iso_l1$np, yaxt = "n")
plot(emp_variog_iso_a2$dist, emp_variog_iso_a2$gamma, ylim=c(0,2500),main="Semivarianz Lichtwert und organische Substanz Horizont 2 Ackerland", ylab = "Semivarianz", xlab = "Distanz" )
points(emp_variog_iso_l2$dist, emp_variog_iso_l2$gamma, col = "red", add=T, labels=emp_variog_iso_l2$np)
Thanks for any help!!!
You can use variogramLine() for this:
VL=variogramLine(YourVariogramFit, maxdist = ...)
next, add it to your plot with lines()
lines(VL)

R script that generates pdf in SSIS

I have SSIS package that gets data into database and then executes R Script. R script creates new folder (names it based on the current date) and generate some pdf files into this folder. I have deployed this package on server and created Job that executes it every night. The problem is that each morning I am finding only empty folders (with correct date name) without any pdf files. However, If I execute that package manually in Visual Studio it works fine and pdfs are there. Am I missing something here? I appreciate every answer.
EDIT
When I execute manually it is directly on the server
Package looks like this
and here is my R script
dir.create(file.path(output.path, date))
library(RODBC)
conn <- odbcConnect("Azure", uid = "aaaaa", pwd = "aaaaa")
etldata <- sqlFetch(conn,"dbo.EtlLogsData", stringsAsFactors = FALSE)
pdf(paste('ETL_Duration_For_Effective_Date_', date,'.pdf',sep = ""),
width = 12,
height = 8,
paper = 'special')
par(mar = c(5, 17, 5, 3))
plot(c(min(etldata_day$st_sec), max(etldata_day$et_sec)),
c(sn[1], sn[1]),
ylim = c(0, n),
yaxt = 'n',
xaxt = 'n',
ylab = '',
xlab = 'Time',
main = paste('ETL Duration With Effective Date ', date, sep = ""))
abline(h = sn, untf = FALSE, col = "gray90")
for (i in 1:n){
lines(c(etldata_day$st_sec[i], etldata_day$et_sec[i]),
c(sn[i], sn[i]),
type = "l", lwd = 2)
arrows(etldata_day$st_sec[i], sn[i],
etldata_day$et_sec[i], sn[i],
length = 0.025, angle = 90, lwd = 2)
arrows(etldata_day$et_sec[i], sn[i],
etldata_day$st_sec[i], sn[i],
length = 0.025, angle = 90, lwd = 2)
}
# Print y axis labels
axis(2, at = sn, labels = etldata_day$TaskName, las = 1, cex.axis = 1)
# Print x axis labels
xat <- seq(from = min(etldata_day$st_sec), to = max(etldata_day$et_sec), length.out = 10)
xlabels <- secondsToString(xat)
axis(1, at = xat, labels = substr(xlabels,1,8), cex.axis = 1)
dev.off()
After plot() I use some FOR cycles, and LINES(),

How to change the color and width of lines with par function in R

I have a question about the par function in R.
I want to change the color and/or width of a line in a graph with par function. (I am using par function because the gaps.plot command below does not allow "col" option to be included. The gaps.plot command is used after the synth command).
So, I used the following command. But I noticed that the lines of the BOX are changed rather than the lines of the GRAPHS.
synth1<-read.csv(file="C:\\Users\\Research\\R\\synthinR_v4.csv",header=TRUE)
attach(synth1)
library("Synth")
dataprep.out34 <- dataprep(foo = synth1, predictors = c("lncdsales", "md1", "md2","md3", "md4", "md5", "md6", "md7", "md8", "md9", "md10", "md11", "yd1", "yd2", "yd3", "yd4", "yd5", "yd6", "yd7", "yd8"), predictors.op = "mean", time.predictors.prior = -13:1, dependent = "lndigital", unit.variable = "artistalbumcode", time.variable = "release", treatment.identifier = 34, controls.identifier = c(1:33, 35:49), time.optimize.ssr = -13:1, time.plot = -13:25)
synth.out34 <- synth(data.prep.obj = dataprep.out34, method = "BFGS")
par(lwd = 2, col="#cccccc")
gaps.plot(synth.res = synth.out34, dataprep.res = dataprep.out34, Ylab = " Log Digital Sales ", Xlab = "Release", Ylim = c(-7, 7) , Main = NA)
Does anyone know how to fix this problem??
Thank you in advance for your willingness to help. I greatly appreciate it!
The col argument to par sets the default plotting colour (i.e. when col is not explicitly specified in plotting calls), but unfortunately col = "black" is hard-coded into the source of gaps.plot.
You can make a modified copy of the function by either (1) viewing the source (F2 in RStudio, or just executing gaps.plot), editing it and assigning it to a new object, or (2) doing something like the following:
gaps.plot2 <- eval(parse(text=gsub('col = "black"', 'col = "red"',
deparse(Synth:::gaps.plot))))
and then using gaps.plot2 as you would use gaps.plot:
gaps.plot2(synth.res = synth.out34, dataprep.res = dataprep.out34,
Ylab = " Log Digital Sales ", Xlab = "Release", Ylim = c(-7, 7) ,
Main = NA)
Alter the lwd similarly. For example to make lines red and have width of 3, use nested gsub calls like this:
gaps.plot2 <- eval(parse(text=gsub('lwd = 2', 'lwd = 3',
gsub('col = "black"', 'col = "red"',
deparse(Synth:::gaps.plot)))))

Problems saving several pdf files in R

I'm trying to save several xyplots created with a "for" loop in R and I'm not able to get complete pdf files (all files have the same size and I can't open them) if I execute the following loop:
for (i in 1:length(gases.names)) {
# Set ylim;
r_y <- round(range(ratio.cal[,i][ratio.cal[,i]<999], na.rm = T), digits = 1);
r_y <- c(r_y[1]-0.1, r_y[2]+0.1);
outputfile <- paste (path, "/cal_ratio_",gases.names[i], ".pdf", sep="");
dev.new();
xyplot(ratio.cal[,i] ~ data.GC.all$data.time, groups = data.vial, panel =
panel.superpose, xlab = "Date", ylab = gases.names[i], xaxt="n", ylim = r_y);
savePlot(filename = outputfile, type = 'pdf', device = dev.cur());
dev.off();
}
(a previous version was using trellis.device() instead of dev.new() + savePlot())
Do you know why I can't get good pdf files? If I do it "manually" it works... Any idea?
use pdf directly
for (i in seq_along(gases.names)) {
# Set ylim
r_y <- round(range(ratio.cal[,i][ratio.cal[,i]<999], na.rm = T), digits = 1)
r_y <- c(r_y[1]-0.1, r_y[2]+0.1)
outputfile <- paste (path, "/cal_ratio_",gases.names[i], ".pdf", sep="")
pdf(file = outputfile, width = 7, height = 7)
print(xyplot(ratio.cal[,i] ~ data.GC.all$data.time, groups = data.vial,
panel = panel.superpose, xlab = "Date", ylab = gases.names[i],
xaxt="n", ylim = r_y))
dev.off()
}

Resources