How can I export my data as a png using R - r

Edit: adding link to the data being used (https://drive.google.com/open?id=0B0PKu0-SX1JPRW94SXFybFd6N2c)
Before I begin, I apologize if this is a duplicate but I cannot seem to find the answer after hours of research (though it likely exists...). I want to read in data from a .csv file and produce a .png showing the density and data points from a specified working directory. This should be able to run from an isolated environment (e.g. usb drive).
I have my data in a .csv file. I have produced some images, but not like that found in the following example (See "Figure 2A" from https://www.r-bloggers.com/reproducible-art-with-r/):
ORIGINAL EXAMPLE
set.seed(16211)
rc <- rpoispp(function(x,y){50 * exp(-3*(max(y)-y))}, 100, win=W23)
rcdist <- distmap(rc, dimyx=c(1200, 800))
rc2 <- rpoispp(1/rcdist*50)
rcd <- dirichlet(rc2)
png(filename = "Figure_2A.png", width=6000, height=4000, res=400)
par(mai=c(0,0,0,0))
plot(rcdist, legend=FALSE, main="", frame=FALSE, box=FALSE, ribbon=FALSE)
plot(rcd, add=T)
plot(rc, add=T, col="black", pch=19, cex=2.5)
plot(rjitter(rc, 0.01), add=T, col="white", pch=19, cex=0.4)
contour(rcdist, add=T, col="white")
dev.off()
I however want my code to produce a similar graph but not using random points. As I sit here delirious from lack of sleep... the best I have come up with is below (and I know it is probably hideous). Any corrections would be much appreciated.
CURRENT ATTEMPT
# load workspace ----------------------------------------------------------
getwd()
setwd("D:/AH_DataToPng_Test/")
# install packages --------------------------------------------------------
install.packages("spatstat")
# load library ------------------------------------------------------------
library(spatstat)
# import my data ----------------------------------------------------------
my.data=read.csv("Figure.csv")
# view in table -----------------------------------------------------------
grid.table(my.data) #Visually confirms data input
# print the data using ppp ------------------------------------------------
# TODO: Answer - Is ppp(xdata, ydata, xrange, yrange) strictly for use in the "Plots" view window?
my.pattern <- ppp(my.data[,1],
my.data[,2],
c(-6,6),
c(-5.1,4.13))
# plot(my.pattern) #TODO: DOESN'T WORK... needed to plot the points?
# plot(density(my.pattern)) #TODO: DOESN'T WORK... needed to produce the neat color graph?
#TODO: Answer - How do I get both the points and density to display simultaneously?
# print the data to png ---------------------------------------------------
png(filename="AH_FinalProjectOutput.png",
units="in",
width=11,
height=8.5,
pointsize=12,
res=72)
# plot(my.data) DOESN"T WORK... NOT NEEDED FOR png()?
# pause for review --------------------------------------------------------
for(i in 1:9){
Sys.sleep(1)
}
dev.off()

png(file="example%02d.png", width=200, height=200)
for (i in c(10:1, "G0!")){
plot.new()
text(.5, .5, i, cex = 6)
}
dev.off()
For me this will create 11 png files in the working directory.

Related

How do you save matplot in R as eps?

I am trying to save a matplot as eps on R. So far all the instructions I have been able to find online were either for the matplotlib in Python or they were something along the lines of saving the graph by right clicking directly, or by using the lines of code:
jpeg("name.jpg")
matplot(t, r[,1:n], type="l", lty=1, ylab="",xlab="Year")
dev.off()
But the quality/resolution of these saved graphs are dreadful. I was hoping something similar to
setEPS()
postscript("name.eps")
matplot(t, r[,1:n], type="l", lty=1, ylab="",xlab="Year")
dev.off()
But unfortunately this does not seem to work for matplot.
A jpeg file is a highly compressed file that loses information. It is never useful for graphics that will be printed or edited. In addition the default size and quality is small and low so you could have improved your results by printing a larger image at higher quality (see ?jpeg for details).
A postscript file (EPS) preserves the information lost by creating a jpeg file and stores the instructions for drawing the image, not a bitmap of the image. It is not clear what you problems were, but here is a simple example:
First, always provide reproducible data:
set.seed(42)
t <- 1950:1975
r1 <- rnorm(26, 35, 5)
r2 <- rnorm(26, 50, 5)
r3 <- rnorm(26, 65, 5)
r <- cbind(r1, r2, r3)
Now the plot:
setEPS()
postscript("name.eps")
matplot(t, r[, 1:3], type="l", lty=1, ylab="",xlab="Year")
dev.off()
readLines("name.eps", 10) # Check the results
# [1] "%!PS-Adobe-3.0" "%%DocumentNeededResources: font Helvetica" "%%+ font Helvetica-Bold"
# [4] "%%+ font Helvetica-Oblique" "%%+ font Helvetica-BoldOblique" "%%+ font Symbol"
# [7] "%%DocumentMedia: a4 595 841 0 () ()" "%%Title: R Graphics Output" "%%Creator: R Software"
# [10] "%%Pages: (atend)"

plot density of multiple csv files of different size in R

I have multiple csv files, each with a single column.
I want to read them and plot their density distribution in a single plot.
can anyone help me?
There are answers elsewhere about
reading multiple csv files so I will mainly concentrate on the density plotting part. Since you did not provide any data, I will use the built-in iris data to create some example files. This first step is to make a reusable example. I am assuming that you already have the data on the disk and have a list of the file names.
## Create some test data
FileNames = paste(names(iris[,1:4]), ".csv", sep="")
for(i in 1:4) {
write.csv(iris[,i], FileNames[i], row.names=FALSE)
}
So, on to the density plots. There is one small sticky point. Each of the different density plots will cover a different range of x and y values. If you want them all in one plot, you will need to leave enough room in your plot to hold them all. The code below first computes that range, then makes the plots.
## Read in all of the data from csv
DataList = list()
for(i in seq_along(FileNames)) {
DataList[[i]] = read.csv(FileNames[i], header=T)[[1]]
}
## Find the range that we will need to include all plots
XRange = range(DataList[[1]])
YRange = c(0,0)
for(i in seq_along(DataList)) {
Rx = range(DataList[[i]])
XRange[1] = min(XRange[1], Rx[1])
XRange[2] = max(XRange[2], Rx[2])
YRange[2] = max(density(DataList[[i]], na.rm=T)$y, YRange[2])
}
## Now make all of the plots
plot(density(DataList[[1]], na.rm=T), xlim=XRange, ylim=YRange,
xlab=NA, ylab=NA, main="Density Plots")
for(i in seq_along(DataList)) {
lines(density(DataList[[i]], na.rm=T), col=i)
}
legend("topright", legend=FileNames, lty=1, col=1:4, bty='n')

R: a faster way to export plots as .pngs with a lot of data?

I am plotting a lot of data in R in a loop and export the plots to png in 300dpi resolution using png(). With all my data I am creating about 2000 plots in the end. This takes about 15 minutes to execute. When exporting to postscript using postscript() it takes about 20 seconds to process the whole data. The approximate file size for a resulting .png is about 300KB and for a .ps it is about 5KB
Is anyone aware of a faster png export method than this? Thank you for your suggestions.
# Plot NAME and ID as filename
for(i in 1:length(ind)){
png(names(ind[i]), width=3358, height=2329, res=300)
# if postscript; uncomment following line
# postscript(names(ind[i]))
par(mar=c(6,8,6,5))
plot(ind[[i]][,c('YEAR','VALUE')],
type='b',
main=ind[[i]][1,'NAME'],
xlab="Time [Years]",
ylab="Value [mm]")
dev.off()
}
So a reproduicible example would be:
dir.create("DummyPlots")
setwd("DummyPlots")
system.time( for(i in 1:500)
{ png(paste0("Image", i, ".png")) ; plot( i ) ; dev.off() })
# 7.5 s
Here's a way that's a little faster:
system.time( {png("FastImage%03d.png")
for(i in 1:500)
plot( i )
dev.off() })
# 5.2 s
setwd("..")
unlink("DummyPlots", recursive=TRUE)

Copying plot with type=n in R to PDF doesn't copy plot points, only it's lines are shown in output pdf

I've encountered a small complication with copying following example of random data to pdf. I realized that it is possible to copy it to png and probably to other bitmap formats as well but not to pdf.
I was trying to learn via this example how to plot "Males" and "Females" on a plot and show them all with different colors, etc.
My device is windows.
x<- rnorm(100)
y<- x+rnorm(100)
g<- gl(2,50)
g<- gl(2,50, labels = c("Male","Female"))
str(g)
plot(x,y)
# Plot function of (x,y) above will display it but it's not clear who is women and who is men, so I do following steps to plot it with different colors.
# Plotting it with type="n".
plot(x,y, type="n")
points(x[g=="Female"], y[g=="Male"], col = "blue")
points(x[g=="Male"], y[g=="Female"], col = "green", pch=19)
fit<- lm(x~y)
abline(fit)
# Now I try to Copy it to png and that works fine.
dev.copy(png,"myfile.png",width=8,height=6,units="in",res=100)
dev.off()
# Now to pdf. This example doesn't work at all abd pdf won't even open in my pdf viewer.
pdf("myfile.pdf",width=8,height=6)
dev.off()
# So I try this and I am able to open it but only "abline" and "x" and "y" are present not the points I specified for males and females.
dev.copy2pdf(file="Examp1.pdf",out.type = "pdf")
dev.off()
Do you have any idea why is this happening? PNG would be sufficient probably but it has it's flaws. So any idea how to copy it to pdf in R?
Thank you for your answers.
Just use:
pdf("myfile.pdf",width=8,height=6)
plot(x,y, type="n")
points(x[g=="Female"], y[g=="Male"], col = "blue")
points(x[g=="Male"], y[g=="Female"], col = "green", pch=19)
fit<- lm(x~y)
abline(fit)
dev.off()
Explanation: This opens a pdf device, plots to it and closes the device.
As I reported in my comment, This works fine, because I copy the original screen device and not the copied png device into pdf device. Note that device copy functions can copy only screen device and when you copy a device this becomes the current one.
windows()
x<- rnorm(100)
y<- x+rnorm(100)
g<- gl(2,50)
g<- gl(2,50, labels = c("Male","Female"))
str(g)
plot(x,y)
plot(x,y, type="n")
points(x[g=="Female"], y[g=="Male"], col = "blue")
points(x[g=="Male"], y[g=="Female"], col = "green", pch=19)
fit<- lm(x~y)
abline(fit)
dev.copy(png,"myfile.png",width=8,height=6,units="in",res=100)
dev.off()
# How many devices are in list?
print (dev.list())
# I must copy only screen device, that there is the previous one
dev <- dev.prev()
# Now it works
dev.copy2pdf(file="Examp1.pdf",out.type = "pdf")
dev.off()

In R, how to prevent blank page in pdf when using gridBase to embed subplot inside plot

As explained here, it is easy to embed a plot into an existing one thanks to gridBase, even though both plots use the base graphics system of R. However, when saving the whole figure into a pdf, the first page is always blank. How to prevent this?
Here is an example:
require(gridBase)
## generate dummy data
set.seed(1859)
x <- 1:100
y <- x + rnorm(100, sd=5)
ols <- lm(y ~ x)
pdf("test.pdf")
## draw the first plot
plot.new() # blank page also happens when using grid.newpage()
pushViewport(viewport())
plot(x, y)
## draw the second plot, embedded into the first one
pushViewport(viewport(x=.75,y=.35,width=.2,height=.2,just=c("center","center")))
par(plt=gridPLT(), new=TRUE)
hist(ols$residuals, main="", xlab="", ylab="")
popViewport(2)
dev.off()
I think it's a bit of a hack but setting onefile=FALSE worked on my machine:
pdf("test.pdf", onefile=FALSE)
In searching for an answer (which I didn't really find so much as stumbled upon in the forest) I came across this post to Rhelp from Paul Murrell who admits that mixing grid and base graphics is confusing even to the Master.
A work around solution I found was to initiate the pdf file inside the for loop; then insert an if clause to assess whether the first iteration is being run. When the current iteration is the first one, go ahead and create the output device using pdf(). Put the dev.off() after closing the for loop. An quick example follows:
for(i in 1:5){
if (i == 1) pdf(file = "test.pdf")
plot(rnorm(50, i, i), main = i)}
dev.off()

Resources