Setting size of the rgl device - r

I have a problem with the fullscreen / non-fullscreen of my rgl device.
Currently I use R 3.00
I plot a persp3d plot (library rgl) into my device, it opens in a quite small window:
The R code:
persp3d(x, y, z, theta=50, phi=25, expand=0.75, col=red,
ticktype="detailed", xlab="", ylab="", zlab="",axes=FALSE)
axes3d(c('x--','z'))
axis3d(edge='y+-',at =c(1,500,1000,1500,2000,2320),
labels =rownames(fd)[c(1,500,1000,1500,2000,2320)])
Which looks like this:
I now rotated it and saved the single png files to my drive. The problem is, that the png files are too small? I want to put them into one paper using LaTex and the \animategraphics command, but it is to pixely (not sharp).
If I click on the fullscreen icon in the rgl device, so that the R plot is larger, this does help and everything works. The problem is, that there is too much white space around it. With this white space above, below, left and right to it I cannot include it in LaTex, because it does not fit because of its big size (width, height). I have 200 png files, so manually removing the white space with paint is not a nice work.
The small pictures look like this:
The following happens, if you zoom in (this is, what LaTex does, when I put it into my paper, it increases the picture, screenshot is from my LaTex file. Same picture, a slightly different angle, but the problem stays the same):
You see that it looks pixely (not good). Also you can already see the problem with the large files with too much white space: The small picture with some white space above already destroys my title.
So how could I solve this problem? How can I tell R to use the fullscreen plots but without so much white space around it? When I click on fullscreen and save those pictures everything is fine, except the white space around it.
Here is the png file with too much white space around it (in this screenshot there is no white space below, but when I use the correct zoom it is there):
One further note: This is the R code I use to save the png- files:
M <- par3d("userMatrix")
movie3d( spin3d(rpm=3), duration=20,dir="C:/test/movie", clean=FALSE )
play3d( spin3d(rpm=3), duration=20)

Use par3d(windowRect = c(20, 30, 800, 800))

You can inspect the state of the RGL device with par3d. The "whitespace" is controlled by the "windowRect" values. There is an automatic increase in those values as the size of the display is increased;
> par3d("windowRect")
[1] 100 100 356 378
> par3d("windowRect") # made the window have roughly 4 times the area
[1] 137 0 744 544
You can also specify what the corners of the windowRect will be.
?par3d
This should give you control that avoids both the "whitespace problem and the title overlap.
If you want to make the object larger in the viewing window, the rgl.viewpoint function can zoom. Smaller number make objects appear larger.
rgl.viewpoint( zoom = .5 )

It was enough to set r3dDefaults:
r3dDefaults$windowRect <- c(0,50, 800, 800)
plot3d(mdatapc, col=kmeanspc.cluster, size = 10)

I think using aspect3d() might also come in handy.
aspect3d(x=5, y=1 , z =1)
rgl.viewpoint(zoom = .5)

Related

Color gradients in R in PDF and bitmap output

I am struggling to get a visually acceptable color gradient in R (see here for a detailed description of my particular case). The problem, in short, is that while output in the R window looks OK, PDFs show thin, white lines between segments used to generate the gradient.
n <- 100
cc <- colorRampPalette(c("red", "blue"))(n)
plot.new()
par(mar=rep(0,4))
sapply(1:n, function(i) rect((i-1)/n, 0, i/n, 1, col=cc[i], border=NA))
dev.copy2pdf(file="test.pdf")
Here is the result:
You can see the thin, white lines. Their positioning depends on the zoom, so I assume that they are an artifact of how the PDF is displayed. Here the same in another zoom:
Unfortunately, these lines are also visible on a printout. I guess the problem may be with how the coordinates in the PDF get rounded when the vector graphics is rendered to bitmap for display or printing.
A possible solution would be to use segments which overlap with each other. This is acceptable only for solid colors; unfortunately, I would like to use transparent colors in the gradients as well.
What can I do to make my output in PDF better?
This seems to be an issue purely due to the renderer. E.g.:
I don't believe there's anything you can change about the PDF to fundamentally fix the issue. In my case, Adobe Acrobat looked good at any zoom level except at very high zoom (I had to go to 3200% zoom to see white lines).
Also, Chrome and Microsoft Edge seemed to work well.
Have you tried this solution? The first rectangle will take a bigger space and the second will be plotted on the first one thus eliminating the white lines behind it. The pdf that Ive got does not show white lines
n <- 100
cc <- colorRampPalette(c("red", "blue"))(n)
plot.new()
par(mar=rep(0,4))
sapply(1:n, function(i) rect((i-1)/n, 0, (i + 1)/n, 1, col=cc[i], border=NA))
dev.copy2pdf(file="test.pdf")
This is zoomed in at 6400 percent

change the font size and margin of R graph

I am experimenting with the investigate_var_importance in package of bartMachine
investigate_var_importance(bart_machine_cv, num_replicates_for_avg = 20)
It turns out that the generated graph is so big, especially the text label along with the x-axis. The default [R Graphics: Device 2(Active) cannot even hold the whole picture. How to change the font size and margin of this plot?
margin can be set by par(mar=c(bottomMargin, left, up, right))
see par to set that parameter
c(0,0,0,0) will not leave any space. You might not want this, as there wouldn't be any space for the axis.
par(oma=c(bottomMargin, left, up, right))
sets the outer margins of the plot
if you send the plot to a pdf, you can increase the size of the plot, which will be able to hold the whole plot i.e,
pdf('nameOfplot.pdf', 20, 6) ## opens a device, and produces a file much wider than longer
plot whater you want
dev.off() ## closes the device you have opened with pdf
if you play with those parameters you might be able to fit your plot

How to do a ridiculously wide plot

I have a long time series of 10000 observations that I want to visualize. The problem is, if I just plot it normally the time-dimension will be squished and none of the fine detail of the time-series that I want to visualize will be apparent. For example:
plot((sin(1:10000/100)+rnorm(10000)/5),type='l')
What I would like is to somehow plot the following together side by side in one gigantically long plot without using par(mfrow=c(1,100)). I then want to export this very wide plot and simply scroll across to vizualise the whole series.
plot((sin(1:10000/100)+rnorm(10000)/5)[1:100],type='l')
plot((sin(1:10000/100)+rnorm(10000)/5)[101:200],type='l')
plot((sin(1:10000/100)+rnorm(10000)/5)[201:300],type='l')
.....
Eventually I would like to have 3 or 4 of these gigantically wide plots on top of each other with a par(mfrow=c(4,1)).
I know that the answer has something to do with the pin setting in par, but I keep getting Error in plot.new() : plot region too large. I'm guessing this has something to do with the interaction of pin with the other par parameters
Bonus points are awarded if we can get the pixel height and width exactly right. It is preferable that the plot doesn't skip random pixels due to the export sizing being imperfect.
Further bonus points if the image can be encoded in a .html. and viewed this way
An alternative that you might consider is svg, which will produce something of better quality than png/jpeg in any case.
Something like
svg(width = 2000, height = 7)
par(mfrow=c(4,1), mar = c(4, 4, 0, 2))
for (i in 1:4){
plot((sin(1:10000/100)+rnorm(10000)/5),type='l',
bty = "l", xaxs = "i")
}
dev.off()
will produce a very wide plot, just over 1MB in size, which renders quite nicely in Chrome.
Note the width and height are in inches here.
P.S. svg also offers the potential for interactive graphics. Just seen a nice example allowing the user to select a region of a long time series to zoom in on, see Figure 22 in Dynamic and Interactive R Graphics for the Web: The gridSVG Package, a draft paper by Paul Murrell and Simon Potter.
It could be a Cairo-specific problem, or it could be a lack of RAM on your machine. The following code works fine for me on a Windows 7 machine with 8GB RAM.
png("wide.png", width = 1e5, height = 500)
plot((sin(1:10000/100)+rnorm(10000)/5),type='l')
dev.off()
If I change the width to 1e6 pixels, then R successfully creates the file (it took about a minute), but no image viewing software that I have available can display an image that large.
I would go on some alternative route. First of all, what exactly is the point of viewing the entire plot at hi-res? If you're searching for some sort of anomalies or irregularities, well, that's what data processing is for :-) . Think about something like finding allx > 3sigma, or doing an FFT, etc.
Next, if you really want to examine the whole thing by eye, how about writing some R-TclTK code or using dynamicGraph or iplots or zoom to produce an interactive graph that you can scroll thru "live."
ETA: IIRC RStudio has tools for interactive graph scrolling and zoom as well.

Creating high-resolution figures in R

This is such a basic problem that's driving me crazy. When generating a figure in R it looks great on the screen. But when I try to generate it directly onto a file using png(), tiff(), etc. by setting the resolution to 300 and the width and height to reasonable values that would suit a journal paper well, there are 2 problems:
All lines are made super thick
All letters are in huge font.
This has been really annoying, I've tried playing with the pointsize option, it helps make the font size smaller, but the line widths are still thick and ugly. Can you please suggest what's going on wrong in R and how I can fix this? I've looked around and most solutions involve using other image processing software. I'd rather figure out why R does this when increasing the resolution and why it makes the figures so ugly. Here's an example:
png(file="test.png",width=5,height=5,units="cm",res=300)
plot(rnorm(1000),rnorm(1000),xlab="some text")
dev.off()
Thanks!
I think the issue is with the default point size (see parameter pointsize in ?png):
Here's what you had with the default of 12:
But if you lower it down to 6:
png(file="test.png",width=5,height=5,units="cm",res=300, pointsize=6)
plot(rnorm(1000),rnorm(1000),xlab="some text")
dev.off()
The way I understand it, a pointsize of 12 means that a text at cex=1 is 12/72th (i. e. 1/6th) of an inch. Your png being ca. 2 inches, your text is therefore 1/12th of the plot width with the default pointsize.

Error in plot.new() : figure margins too large in R

I'm new to R but I've made numerous correlation plots with smaller data sets. However, when I try to plot a large dataset (2gb+), I can produce the plot just fine, but the legend doesn't show up. Any advice? or alternatives?
library(gplots)
r.cor <- cor(r)
layout(matrix(c(1,1,1,1,1,1,1,1,2,2), 5, 2, byrow = TRUE))
par(oma=c(5,7,1,1))
cx <- rev(colorpanel(25,"yellow","black","blue"))
leg <- seq(min(r.cor,na.rm=T),max(r.cor,na.rm=T),length=10)
image(r.cor,main="Correlation plot Normal/Tumor data",axes=F,col=cx)
axis(1, at=seq(0,1,length=ncol(r.cor)), labels=dimnames(r.cor)[[2]],
cex.axis=0.9,las=2)
axis(2,at=seq(0,1,length=ncol(r.cor)), labels=dimnames(r.cor)[[2]],
cex.axis=0.9,las=2)
image(as.matrix(leg),col=cx,axes=T)
Error in plot.new() : figure margins too large
tmp <- round(leg,2)
axis(1,at=seq(0,1,length=length(leg)), labels=tmp,cex.axis=1)
This error can occur in Rstudio simply because your "Plots" pane is just barely too small. Try zooming your "Files, Plots, Packages, Help, Viewer" and see if it helps!
The problem is that the small figure region 2 created by your layout() call is not sufficiently large enough to contain just the default margins, let alone a plot.
More generally, you get this error if the size of the plotting region on the device is not large enough to actually do any plotting. For the OP's case the issue was having too small a plotting device to contain all the subplots and their margins and leave a large enough plotting region to draw in.
RStudio users can encounter this error if the Plot tab is too small to leave enough room to contain the margins, plotting region etc. This is because the physical size of that pane is the size of the graphics device. These are not independent issues; the plot pane in RStudio is just another plotting device, like png(), pdf(), windows(), and X11().
Solutions include:
reducing the size of the margins; this might help especially if you are trying, as in the case of the OP, to draw several plots on the same device.
increasing the physical dimensions of the device, either in the call to the device (e.g. png(), pdf(), etc) or by resizing the window / pane containing the device
reducing the size of text on the plot as that can control the size of margins etc.
Reduce the size of the margins
Before the line causing the problem try:
par(mar = rep(2, 4))
then plot the second image
image(as.matrix(leg),col=cx,axes=T)
You'll need to play around with the size of the margins on the par() call I show to get this right.
Increase the size of the device
You may also need to increase the size of the actual device onto which you are plotting.
A final tip, save the par() defaults before changing them, so change your existing par() call to:
op <- par(oma=c(5,7,1,1))
then at the end of plotting do
par(op)
If you get this message in RStudio, clicking the 'broomstick' figure "Clear All Plots" in Plots tab and trying plot() again may work.
This sometimes happen in RStudio. In order to solve it you can attempt to plot to an external window (Windows-only):
windows() ## create window to plot your file
## ... your plotting code here ...
dev.off()
I got this error in R Studio, and was simply fixed by making the sidebar bigger by clicking and dragging on its edge from right to left.
Picture here: https://janac.medium.com/error-in-plot-new-figure-margins-too-large-in-r-214621b4b2af
Check if your object is a list or a vector. To do this, type is.list(yourobject). If this is true, try renaming it x<-unlist(yourobject). This will make it into a vector you can plot.
Just zoom this area if you use RStudio.
I found this error today. Initially, I was trying to output it to a .jpeg file with low width and height.
jpeg("method1_test.jpg", width=900, height=900, res=40)
Later I increased the width and height to:
jpeg("method1_test.jpg", width=1900, height=1900, res=40)
The error was not there. :)
You can also play with the resolution, if the resolution is high, you need more width and height.
I had this error when I was trying to plot high dimensional data. If that's what is going on with you, try multidimensional scaling: http://www.statmethods.net/advstats/mds.html
I struggled with this error for weeks (using RStudio). I tried moving the plot window bigger and smaller, but that did not consistently help. When I moved (dragged) the application to my bigger monitor, the problem disappeared! I was stunned... so many wasted hours... I knew my code was correct...
If margin is low, then it is always better to start with new plotting device:
dev.new()
# plot()
# save your plot
dev.off()
You will never get margin error, unless you plot something large which can not be accommodated.
RStudio Plots canvas is limiting the plot width and heights. However if you make your plot from Rmarkdown code chunk, it works without canvas field limitation because plotting area set according to the paper size.
For instance:
```{r}
#inside of code chunk in Rmarkdown
grid <- par(mfrow=c(4, 5))
plot(faithful, main="Faithful eruptions")
plot(large.islands, main="Islands", ylab="Area")
...
par(grid)
```
I found the same error today. I have tried the "Clear all Plots" button, but it was giving me the same error. Then this trick worked for me,
Try to increase the plot area by dragging. It will help you for sure.
I have just use the Clear all plots then again give the plot command and it was helpfull

Resources