I am still new to R and I have searched around for a solution to my simple question, but I haven't found an answer that I've been able to get to work. I am looking to use a previously identified variable per data set, here variable=SNPname to include in script for automated generation of graph output in png format.
I am using this to generate a kmeans plot and have:
(cl <- kmeans(FilteredData[,6:7], 5, nstart=25))
png("C:/temp/$SNPnamegraph1.png") #SNPname to include in filename
plot(FilteredData[,6:7], col=cl$cluster)
points(cl$centers, col=1:5, pch=8)
dev.off()
where I want to include that variable in line 2 at the beginning of the file name. Is there a simple way to do this that I am just missing?
Close, you're just missing the use of paste() and setwd()
setwd("C:/temp/") # use this to set where you want things saved
...
c1 <- kmeans...
png(paste(SNPname, " graph1.png", sep=""))
...
If it's in a loop of some kind, you might need to use SNPname[loop_var]
Related
I've made different plots (more than a hundred) for a project and I haven't capture them on the way (yes it's bad , i know). Now, I need to save them all at once but without running again my script (which takes hours). Is there a way to do so within Rstudio ?
Edit: All the plot are already there and I don't want to run them again.
In RStudio, every session has a temporary directory that can be obtained using tempdir(). Inside that temporary directory, there is another directory that always starts with "rs-graphics" and contains all the plots saved as ".png" files. Therefore, to get the list of ".png" files you can do the following:
plots.dir.path <- list.files(tempdir(), pattern="rs-graphics", full.names = TRUE);
plots.png.paths <- list.files(plots.dir.path, pattern=".png", full.names = TRUE)
Now, you can copy these files to your desired directory, as follows:
file.copy(from=plots.png.paths, to="path_to_your_dir")
Additional feature:
As you will notice, the .png file names are automatically generated (e.g., 0078cb77-02f2-4a16-bf02-0c5c6d8cc8d8.png). So if you want to number the .png files according to their plotting order in RStudio, you may do so as follows:
plots.png.detials <- file.info(plots.png.paths)
plots.png.detials <- plots.png.detials[order(plots.png.detials$mtime),]
sorted.png.names <- gsub(plots.dir.path, "path_to_your_dir", row.names(plots.png.detials), fixed=TRUE)
numbered.png.names <- paste0("path_to_your_dir/", 1:length(sorted.png.names), ".png")
# Rename all the .png files as: 1.png, 2.png, 3.png, and so on.
file.rename(from=sorted.png.names, to=numbered.png.names)
Hope it helps.
Although this discussion has been inactive for a while, there are some persons, like myself, who still come across the same problem, and the other solutions don't really seem to even get what the actual question is.
So, hands on. Your plot history gets saved in a variable called .SavedPlots. You can either access it directly, assign it to another variable in code or do the latter from the plots window.
# ph for plot history
ph <- .SavedPlots
In R 3.4.2, I could index ph to reproduce the corresponding plot in a device. What follows is rather straightforward:
Open a new device (png, jpeg, pdf...).
Reproduce your plot ph[index_of_plot_in_history].
Close the device (or keep plotting if it is a pdf with multiple pages).
Example:
for(i in 1:lastplot) {
png('plotname.png')
print(ph[i])
dev.off()
}
Note: Sometimes this doesn't happen because of poor programming. For instance, I was using the MICE package to impute many datasets with a large number of variables, and plotting as shown in section 4.3 of this paper. Problem was, that only three variables per plot were displayed, and if I used a png device in my code, only the last plot of each dataset would be saved. However, if the plots were printed to a window, all the plots of each dataset would be recorded.
If your plots are 3d, you can take a snapshot of all your plots and save them as a .png file format.
snapshot3d(filename = '../Plots/SnapshotPlots.png', fmt = 'png')
Or else, the best way is to create a multi-paneled plotting window using the par(mfrow) function. Try the following
plotsPath = "../Plots/allPlots.pdf"
pdf(file=plotsPath)
for (x in seq(1,100))
{
par(mfrow = c(2,1))
p1=rnorm(x)
p2=rnorm(x)
plot(p1,p2)
}
dev.off()
You can also use png, bmp, tiff, and jpeg functions instead of pdf. You can read their advantages and disadvantages and choose the one you think is good for your needs.
I am not sure how Rstudio opens the device where the plot are drawn, but I guess it uses dev.new(). In that case one quick way to save all opened graphs is to loop through all the devices and write them using dev.print.
Something like :
lapply(dev.list(),function(d){dev.set(d);dev.print(pdf,file=file.path(folder,paste0("graph_",d,".pdf"))})
where folder is the path of the folder where you want to store your graph (could be for example folder="~" if you are in linux and want to store all your graph in your home folder).
If you enter the following function all that will follow will be save in a document:
pdf("nameofthedocument.pdf")
plot(x~y)
plot(...
dev.off()
You can also use tiff(), jpg()... see ?pdf
This is very elementary for those who use R... (But I do stats with Stata and Mplus.)
I develop many plots (638 in total) and want to save all in separate files. It worked well first, not now
for(i in 001:638){
## command for plot comes here, including mentioning of i ##
dev.copy(png,'plot-%d.png')
dev.off()
}
I want one file for each plot, but end up with a single plot file (plot_1.png), with only the last plot.
Christopher
png function will do this by default. For example, this will create 10 plots in your working directory.
png("plot-%d.png")
for(i in 1:10) plot(1:i)
dev.off()
You'll want to use one of the paste() functions to create your string.
Since you didn't provide a reproducible example I can only guess, but I think that something like this would probably work.
paste("plot",i,".png", sep = "")
in place of your current use of c style % replacement. So this
for(i in 001:638){
#command for plot comes here, including mentioning of i ##
dev.copy(png,paste("plot",i,".png", sep = ""))
dev.off()
}
I am trying to create a loop in R that does the following. I have a map with for example 10 datasets: file1.txt.csv, file2.txt.csv, etc. Now I simply want to create one graph per data set and output that, so that I get file1.jpeg, file2.jpeg, etc.
This is what I got so far:
fileNames <- Sys.glob("*.txt.csv")
for (fileName in fileNames) {
VolumeData <- read.delim(fileName, header = FALSE)
# convert data frame to data table
VolumeDatat <- VolumeData [, -(7:14)]
# set column names
setnames(VolumeDatat, c("MCS", "cell_type", "cell_number", "total_volume"))
jpeg(sub(".txt.csv",".jpg"))
plot(VolumeDatat$total_volume~VolumeDatat$MCS,type="l")
dev.off()
}
And I guess that
jpeg (sub(".txt.csv",".jpg"))
is the essential part for this, but I can't figure this out, also the arguments for jpeg in the library didn't help me much further.
First, I tried with jpeg (fileName.jpeg), which works, but only for the last file in the loop as the file gets overwritten for each time you run the script, e.g. each file.
So now I tried it with some sub-function, cause I thought that might work, but by doing so, I got:
Error in sub(".txt.csv", ".jpg") :
argument "x" is missing, with no default
Could anyone help me with this? I'd be very grateful!
I am doing java and R integration using JRI.
Please find below script
String path = "C:\\Users\\hrpatel\\Desktop\\CSVs\\DataNVOCT.csv";
rengine.eval("library(tseries)");
rengine.eval(String.format("mydata <- read.csv('%s')",path.replace('\\', '/')));
String exportFilePath= "C:\\Users\\hrpatel\\Desktop\\CSVs\\arima3.jpg";
rengine.eval("Y <- NewVisits");
rengine.eval("t <- Day.Index");
rengine.eval("summary(Y)");
rengine.eval("adf.test(Y, alternative='stationary')");
rengine.eval("adf.test(Y, alternative='stationary', k=0)");
rengine.eval("acf(Y)");
rengine.eval("pacf(Y)");
rengine.eval("mydata.arima101 <- arima(Y,order=c(1,0,1))");
rengine.eval("mydata.pred1 <- predict(mydata.arima101, n.ahead=1000)");
rengine.eval(String.format("jpeg('%s')",exportFilePath.replace('\\', '/')));
rengine.eval("plot(t,Y)");
rengine.eval("lines(mydata.pred1$pred, col='blue',size=10)");
rengine.eval("lines(mydata.pred1$pred+1*mydata.pred1$se, col='red')");
rengine.eval("lines(mydata.pred1$pred-1*mydata.pred1$se, col='red')");
rengine.eval("dev.off()");
In above codebase when i tried plot(t,Y) or plot(Y). it export a blank image, while in case of plot(mydata) it is working file.
One more thing when i run above code in R it creates the image(using JRI it shows blank image).
I have spend 1 day to solve this but i dont found any solution.
Please suggest if you have any alternatives.
Your help is needed.
Thanks in Advance
if i understand correctly, you have a data set named mydata, that has two columns, NewVisits, and Day.Index, in that case you need to change:
rengine.eval("Y <- NewVisits");
to
rengine.eval("Y <- mydata$NewVisits");
and
rengine.eval("t <- Day.Index");
to
rengine.eval("t <- mydata$Day.Index");
This also explains why plot(mydata) works for you - because R recognizes it.
if this isn't the solution, then i cant see where you are reading NewVisits and Day.Index from
BTW i stongly recommend to plot using the ggplot package
Is there a way to have an R Device (postscript would be great) write the output into a variable instead of a file?
For example I know this:
postscript(file="|cat")
plot(1:10)
dev.off()
Will send the postscript text to STDOUT. How can I get that text into a variable within R?
I've had success in getting the Binary of a plot into an R variable as a string. Its got some read/write overhead. In the snippet below, R saves the plot as a temp file and reads it back in.
## create a plot
x <- rnorm(100,0,1)
hist(x, col="light blue")
## save plot as temp file
png(filename="temp.png", width=500, height=500)
print(p)
dev.off()
## read temp file as a binary string
plot_binary <- paste(readBin("temp.png", what="raw", n=1e6), collapse="")
Maybe this is helpful to you.
postscript takes a command argument, hence postscript(file="",command="|cat")
Why on earth would you want to do that? R is not a very good system for manipulating Postscript files. If nothing else, you can use tempfile() to write the image to a file, which you can then read in using standard file functions. If you wanted to be fancy, you could perhaps use fifo() pipes, but I doubt it'll be much faster. But I suspect you'd be better off with a different approach.
You should be able to use a textConnection as follows.
tc <- textConnection("string", "w")
postscript(tc)
plot(1:10)
dev.off()
But string remains blank - maybe a bug?