"Error in plot.new() : figure margins too large" - r

In R, I met a running error as follows:
> png("p3_sa_para.png", 4, 2)
> par(mfrow=c(1,2))
> plot(c(1:10), ylab="Beta",xlab="Iteration")
Error in plot.new() : figure margins too large
> plot(c(1:10), ylab="Gamma",xlab="Iteration")
Error in plot.new() : figure margins too large
> dev.off()
X11cairo
2
I have already made the image size small to be 4 by 2, why it still complains "figure margins too large"? How can I solve this problem with png?
It is strange that if I change png to pdf, then it will work. I also wonder why?
Thanks and regards!

The png() function uses pixels not inches, so try something like
png("p3_sa_para.png", 640, 480)
And to answer your second question, yes, pdf() uses inches because a vector-graphics format has no notion of pixels. The help(png) and help(pdf) functions are your friends.

The problem can simply arise from using a certain IDE. I was using Rstudio, and I got a slew of errors. My exact same code worked fine in the console.

Even I was getting the error on R-Studio, while the plot was appearing fine on the console. A simple restart of RStudio solved the problem! Having said that, RStudio's support page suggests that resetting graphics device dev.off() may help. http://support.rstudio.org/help/kb/troubleshooting/problem-with-plots-or-graphics-device

This is a common issue for plotting specially when you are using IDE which has a place for generating and showing you the plot, thought it's a general issue and there is a logic behind it:
when you tell R to plot something, R first look at the data and then looks at the area it has at it's disposal so that it cal do the plotting.
The png() and similar commands:
In your case you gave the plot a 4 by 2 pixel area to plot it, so you can solve it by increasing the area in a size that can fit your plot. (as Dirk Eddelbuettel mentioned)
In case of IDE
This is much simpler in most cases, just increase the plotting area by dragging the margins and then re-run your code (close any par() if you have any opened before and create new one)

Related

Is there a way to set RStudio console output to exactly mimic PDF output

What I am doing is producing a document using rmarkdown and kniting to a PDF. This seems generally a great thing and produces professional looking output. However, it is really frustrating to try and tweak the look of graphics. The preview looks fine in Rstudio, and then when the PDF is generated there is some issue with labels not fitting, etc.
Even though my data is relatively small, and I am only producing a dozen graphs, each knit of the document takes 5 minutes or so. That means a couple of tweaks of a graph takes 15 minutes!
Is there a way to set the default size of the RStudio plot window so this doesn't happen?
Any other tricks to speed up this process?
Thanks,
David
Running dev.new() will open a plot window that is to your specified sizes.
E.g. dev.new(width=5, height=4)
(from related question)
Else you could set the figure sizes for the chunk.
{r, fig.width=5, fig.height=4}
(reference)

scaling the R exported plot to match R's output plot

This may sound weird, or impossible but I can say the scale of the output plot when you compile inside R and view it without zooming or exporting works great for me. However, when I export to pdf, the plot becomes outrageously large and I never manage to scale it to what I see inside R. Am I being silly, or there is actually a difference and there is a way to get what I see inside that bottom-left-corner box of the R.
use ggsaves width and length arguments to get the desired size.
ggsave('name.pdf', width =14, height = 8)

Wrong output size when plotting over an image in R

My goal is to read an image file in either the PNG or JPEG format and plot various data over said image and save it to disk.
I also want the image to take up all available space in the produced plot, no axes or labels or anything. I'm a bit concerned that this might be relevant to my problem.
Code example
Below is my current code that currently only tries to output the same image as you put in. Later I plan on plotting data points corresponding to coordinates over the image. I've used some sample code found here in order to remove the axes and be able to have the image in the background of the plot.
library(jpeg)
library(grid)
img <- readJPEG(system.file("img", "Rlogo.jpg", package="jpeg"),native=TRUE)
jpeg(filename = "Rlogo-2.jpg", width=100,height=76, quality = 100,res=299)
op<-par(mar=rep(0,4))
plot(0:100,type="n", axes="FALSE",ann="FALSE")
lim <- par()
rasterImage(img, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])
dev.off()
Example output
This is an example output of my above code in a comparison with the original image:
The image to the left is the original and the right one is the modified one. As you can see it seems as if the image I read and plot somehow is smaller than the original image and when saved to the original dimensions it appears blurred.
I've been pulling my hair over this one for hours and I don't seem to get anywhere. This is my first attempt to plot data over images and I'm aware of my lack of knowledge about how R represents images and I've mostly been using the basic graphics to do relatively simple plots before.
I'm currently considering doing this in Python instead but I'm afraid that'll come back and bite me when it comes to the actual plotting of the data.
I run R version 3.1.0 on x86_64 running Windows 7.
Just to summarize, since you already found the culprit, there are two issues present here:
Firstly, the blurring appears to be caused by the jpeg device on Windows. There is no such problem on Ubuntu Linux and it disappears if you use the Cairo-device instead, as you did already discover. Cairo-devices are great for pdf:s too since they embed all the fonts etc. making the figure look the same across platforms.
Secondly, R adds 4% extra margin to the x and y axes by default to prevent graphics from being chopped off near the edge of the plot area. It can be corrected by setting xaxs="i" and yaxs="i".
par(mfrow=1:2)
plot(1:5, 1:5) # Left
plot(1:5, 1:5, xaxs="i", yaxs="i") # Right
In your case the difference is subtle but still would cause everything to be slightly misaligned.

Error in plot.new()

I'm using R Studio when doing some GIS plots. Unfortunately I keep getting this same error but only on certain maps.
Error in plot.new() : figure margins too large
I know its an issue with the plotting window size but I'm wondering if there is a way to edit the default settings without having to manually change the window size every time?
You can alter R to plot to a different device, which can let you pop out the plot in a separate window.
A Windows solution:
plot_data <- sample(1:100,100)
windows(width=500,height=500)
plot(plot_data,type="o")
See also this answer.

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