dev.hold, dev.flush and resizing windows - r

In R, it is possible to hold a device, draw the picture, and then flush the device to render the graphics. This is useful for very complex plots with thousands of data points, color gradients etc since without holding, the device would be refreshed after each plotting operation. It works quite well.
However, once the plot is in place, any window operation such as a resize will cause the plot to be refreshed -- however, this time without holding and flushing the device, but plotting the plot elements one by one and refreshing the display each time. This is extremely annoying.
Clearly, I could call manually dev.hold before resizing the window, but this is not a real solution.
Is there a way of telling R that the device should be put on hold for operations such as resize?

As indicated by Dan Slone and gdkrmr viable option is to use intermediate raster file to plot complex graphics.
The flow is the follows:
Save plot to png file.
Plot the image into the screen device.
After this there will be no problems with refreshing and resizing.
Please see the code below:
# plotting through png
plot.png <- function(x, y) {
require(png)
tmp <- tempfile()
png(tmp, width = 1920, height = 1080)
plot(x, y, type = "l")
dev.off()
ima <- readPNG(tmp)
op <- par(mar = rep(0, 4))
plot(NULL, xlim = c(0, 100), ylim = c(0, 100), xaxs = "i", yaxs = "i")
rasterImage(ima, 0, 0, 100, 100, interpolate = TRUE)
par(op)
unlink(tmp)
}
t <- 1:1e3
x <- t * sin(t)
y <- t * cos(t)
# without buffering
# plot(x, y, type = "l")
# with buffering in high-res PNG-file
plot.png(x, y)
Ouput:

Related

non-linear 2d object transformation by horizontal axis

How can such a non-linear transformation be done?
here is the code to draw it
my.sin <- function(ve,a,f,p) a*sin(f*ve+p)
s1 <- my.sin(1:100, 15, 0.1, 0.5)
s2 <- my.sin(1:100, 21, 0.2, 1)
s <- s1+s2+10+1:100
par(mfrow=c(1,2),mar=rep(2,4))
plot(s,t="l",main = "input") ; abline(h=seq(10,120,by = 5),col=8)
plot(s*7,t="l",main = "output")
abline(h=cumsum(s)/10*2,col=8)
don't look at the vector, don't look at the values, only look at the horizontal grid, only the grid matters
####UPDATE####
I see that my question is not clear to many people, I apologize for that...
Here are examples of transformations only along the vertical axis, maybe now it will be more clear to you what I want
link Source
#### UPDATE 2 ####
Thanks for your answer, this looks like what I need, but I have a few more questions if I may.
To clarify, I want to explain why I need this, I want to compare vectors with each other that are non-linearly distorted along the horizontal axis .. Maybe there are already ready-made tools for this?
You mentioned that there are many ways to do such non-linear transformations, can you name a few of the best ones in my case?
how to make the function f() more non-linear, so that it consists, for example, not of one sinusoid, but of 10 or more. Тhe figure shows that the distortion is quite simple, it corresponds to one sinusoid
and how to make the function f can be changed with different combinations of sinusoids.
set.seed(126)
par(mar = rep(2, 4),mfrow=c(1,3))
s <- cumsum(rnorm(100))
r <- range(s)
gridlines <- seq(r[1]*2, r[2]*2, by = 0.2)
plot(s, t = "l", main = "input")
abline(h = gridlines, col = 8)
f <- function(x) 2 * sin(x)/2 + x
plot(s, t = "l", main = "input+new greed")
abline(h = f(gridlines), col = 8)
plot(f(s), t = "l", main = "output")
abline(h = f(gridlines), col = 8)
If I understand you correctly, you wish to map the vector s from the regular spacing defined in the first image to the irregular spacing implied by the second plot.
Unfortunately, your mapping is not well-defined, since there is no clear correspondence between the horizontal lines in the first image and the second image. There are in fact an infinite number of ways to map the first space to the second.
We can alter your example a bit to make it a bit more rigorous.
If we start with your function and your data:
my.sin <- function(ve, a, f, p) a * sin(f * ve + p)
s1 <- my.sin(1:100, 15, 0.1, 0.5)
s2 <- my.sin(1:100, 21, 0.2, 1)
s <- s1 + s2 + 10 + 1:100
Let us also create a vector of gridlines that we will draw on the first plot:
gridlines <- seq(10, 120, by = 2.5)
Now we can recreate your first plot:
par(mar = rep(2, 4))
plot(s, t = "l", main = "input")
abline(h = gridlines, col = 8)
Now, suppose we have a function that maps our y axis values to a different value:
f <- function(x) 2 * sin(x/5) + x
If we apply this to our gridlines, we have something similar to your second image:
plot(s, t = "l", main = "input")
abline(h = f(gridlines), col = 8)
Now, what we want to do here is effectively transform our curve so that it is stretched or compressed in such a way that it crosses the gridlines at the same points as the gridlines in the original image. To do this, we simply apply our mapping function to s. We can check the correspondence to the original gridlines by plotting our new curves with a transformed axis :
plot(f(s), t = "l", main = "output", yaxt = "n")
axis(2, at = f(20 * 1:6), labels = 20 * 1:6)
abline(h = f(gridlines), col = 8)
It may be possible to create a mapping function using the cumsum(s)/10 * 2 that you have in your original example, but it is not clear how you want this to correspond to the original y axis values.
Response to edits
It's not clear what you mean by comparing two vectors. If one is a non-linear deformation of the other, then presumably you want to find the underlying function that produces the deformation. It is possible to create a function that applies the deformation empirically simply by doing f <- approxfun(untransformed_vector, transformed_vector).
I didn't say there were many ways of doing non-linear transformations. What I meant is that in your original example, there is no correspondence between the grid lines in the original picture and the second picture, so there is an infinite choice for which gridines in the first picture correspond to which gridlines in the second picture. There is therefore an infinite choice of mapping functions that could be specified.
The function f can be as complicated as you like, but in this scenario it should at least be everywhere non-decreasing, such that any value of the function's output can be mapped back to a single value of its input. For example, function(x) x + sin(x)/4 + cos(3*(x + 2))/5 would be a complex but ever-increasing sinusoidal function.

"Plot.new has not been called yet" issue using plot() [duplicate]

Why does this happen?
plot(x,y)
yx.lm <- lm(y ~ x)
lines(x, predict(yx.lm), col="red")
Error in plot.xy(xy.coords(x, y), type = type, ...) :
plot.new has not been called yet
Some action, very possibly not represented in the visible code, has closed the interactive screen device.
It could be done either by a "click" on a close-button, or it could also be done by an extra dev.off() when plotting to a file-graphics device. (The second possibility might happen if you paste in a multi-line plotting command that has a dev.off() at the end of it, but had errored out at the opening of the external device. So the dangling dev.off() on a separate line accidentally closes the interactive device).
Some (most?) R implementations will start up a screen graphics device open automatically, but if you close it down, you then need to re-initialize it.
On Windows that might be window(); on a Mac, quartz(); and on a Linux box, x11(). You also may need to issue a plot.new() command. I just follow orders. When I get that error I issue plot.new() and if I don't see a plot window, I issue quartz() as well. I then start over from the beginning with a new plot(., ., ...) command and any further additions to that plot screen image.
In my case, I was trying to call plot(x, y) and lines(x, predict(yx.lm), col="red") in two separate chunks in Rmarkdown file. It worked without problems when running chunk by chunk, but the corresponding document wouldn't knit. After I moved all plotting calls within one chunk, problem was resolved.
As a newbie, I faced the same 'problem'.
In newbie terms :
when you call plot(), the graph window gets the focus and you cannot enter further commands into R. That is when you conclude that you must close the graph window to return to R.
However, some commands, like identify(), act on open/active graph windows.
When identify() cannot find an open/active graph window, it gives this error message.
However, you can simply click on the R window without closing the graph window. Then you can type more commands at the R prompt, like identify() etc.
plot.new() error occurs when only part of the function is ran.
Please find the attachment for an example to correct error
With error....When abline is ran without plot() above
Error-free ...When both plot and abline ran together
I had the same problem... my problem was that I was closing my quartz window after plot(x,y). Once I kept it open, the lines that previously resulted in errors just added things to my plot (like they were supposed to). Hopefully this might help some people who arrive at this page.
If someone is using print function (for example, with mtext), then firstly depict a null plot:
plot(0,type='n',axes=FALSE,ann=FALSE)
and then print with newpage = F
print(data, newpage = F)
I had the problem in an RMarkdown, and putting the offending line on the previous line of code helped.
Minimal Reproducible Example
This will error if run line by line in an Rmd:
x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
colnames(x) <- c("x", "y")
(cl <- kmeans(x, 2))
plot(x, col = cl$cluster)
points(cl$centers, col = 1:2, pch = 8, cex = 2)
but this works:
x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
colnames(x) <- c("x", "y")
(cl <- kmeans(x, 2))
plot(x, col = cl$cluster); points(cl$centers, col = 1:2, pch = 8, cex = 2)
The only change is that the offending line (the last one) is placed after the last succeeding line (placing a ; in between). You can do it for as many offending lines as desired.

Output Stem and Leaf Plot to Image

I'm trying to output a Stem and Leaf plot in R as an image. I'm not sure if there's a nice library which can accomplish this but below is some of the code I've tried.
jpeg(filename="stem.jpeg",width=480,height=480, units="px",pointsize=12)
plot.new()
tmp <- capture.output(stem(men, scale = 1, width = 40))
text( 0,1, paste(tmp, collapse='\n'), adj=c(0,1), family='mono' )
dev.off()
This above code resulted in the data being saved, but it looks very blurry and the plot gets cut off pretty badly. When adding a histogram to an image, R seems to do a good job to scale everything to fit in the size of the image.
jpeg(filename="stem.jpeg",width=480,height=480,
units="px",pointsize=12)
stem(men, scale = 1, width = 40)
dev.off()
This created the image but had no content within it.
Any ideas? Thanks!
That's because stem and leaf plots produce text not images. You can save the text as follows using the sink command: http://stat.ethz.ch/R-manual/R-devel/library/base/html/sink.html
sink(file=“Stem.txt”)
stem(men, scale = 1, width = 40)
sink(file=NULL)
unlink("stem.txt")
To export a stemplot as graphics, you can use a vector graphics format, such
as .eps, .pdf, or .emf. For example, a windows metafile:
win.metafile("stem.wmf", pointsize = 10)
plot.new()
tmp <- capture.output(stem(mtcars$mpg))
text(0,1,paste(tmp,collapse='\n'),family='mono',adj=c(0,1))
dev.off()

R par(omd) does not contain within mfrow

I would like two plots to show up in two seperate spaces in the plot so I do:
par(mfrow=c(1,2))
plot(1:10,1:10)
Now I would like the second plot to be about 25% shorter than the first plot so I adjust omd:
tmp <- par()$omd
tmp[4] <- 0.75
par(omd=tmp)
plot(1:10,1:10)
The problem is that the second plot shows up ontop of the first plot. How do I avoid this margin issue?
Maybe try using layout instead?
layout(matrix(c(1, 1, 0, 2), ncol = 2L), widths = c(1,1),heights = c(0.5,1))
par(mar = c(3,2,2,2))
plot(1:10,1:10)
par(mar = c(3,2,2,2))
plot(1:10,1:10)
I guess maybe you'd want to set the heights to c(0.2,0.8) to get a 25% reduction?
Edit
But I don't think that omd does what you think it does. It changes the region inside the outer margins, which will always include both plot regions when setting par(mfrow = c(1,2)). What you really want to change, I think is plt, which alters the size of the current plotting region (using quartz, as I'm on a mac):
quartz(width = 5,height = 5)
par(mfrow=c(1,2))
vec <- par("plt")
plot(1:10,1:10)
par(plt = vec * c(1,1,1,0.75))
plot(1:5,1:5)

ploting artefact with points over raster

I noticed some weird behavior when resizing the plot window. Consider
library(sp)
library(rgeos)
library(raster)
rst.test <- raster(nrows=300, ncols=300, xmn=-150, xmx=150, ymn=-150, ymx=150, crs="NA")
sap.krog300 <- SpatialPoints(coordinates(matrix(c(0,0), ncol = 2)))
sap.krog300 <- gBuffer(spgeom = sap.krog300, width = 100, quadsegs = 20)
shrunk <- gBuffer(spgeom = sap.krog300, width = -30)
shrunk <- rasterize(x = shrunk, y = rst.test)
shrunk.coords <- xyFromCell(object = rst.test, cell = which(shrunk[] == 1))
plot(shrunk)
points(shrunk.coords, pch = "+")
If you resize the window, plotted points get different extent compared to the underlying raster. If you resize the window and plot shrunk and shrunk.coords again, the plot turns out fine. Can anyone explain this?
If you plot directly with the RasterLayer method for plot the resize problem does not occur.
## gives an error, but still plots
raster:::.imageplot(shrunk)
points(shrunk.coords, pch = ".")
So it must be something in the original plot call before the .imageplot method is called.
showMethods("plot", classes = "RasterLayer", includeDefs = TRUE)
It does occur if we call raster:::.plotraster directly, and this is the function that calls raster:::.imageplot:
raster:::.plotraster(shrunk, col = rev(terrain.colors(255)), maxpixels = 5e+05)
points(shrunk.coords, pch = ".")
It is actually in the axis labels, not the image itself. See with this, this plots faithfully on resize:
raster:::.imageplot(shrunk)
abline(h = c(-80, 80), v = c(-80, 80))
But do it like this, and the lines are no longer at [-80, 80] after resize:
plot(shrunk)
abline(h = c(-80, 80), v = c(-80, 80))
So it is actually the points plotted after the raster that are showing incorrectly: the plot method keeps the aspect ratio fixed, so widening the plot doesn't "stretch" out the raster circle to an ellipse. But, it does something to the points that are added afterwards so the calls to par() must not be handled correctly (probably in raster:::.imageplot).
Another way of seeing the problem is to show that axis() does not know the space being used by the plot, which is the same problem you see when overplotting:
plot(shrunk)
axis(1, pos = 1)
When you resize the x-axis length the two axes are no longer synchronized.
Because you have a raster, try replacing plot() with image(). I had the same problem but this solved it for me.

Resources