Error in plot.new() - r

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.

Related

Adjusting margins for R plots

I'm interesting in adjusting margins for R plots. I use R Studio on MacOS, run on a 2013 intel CPU Macbook pro.
Here is the data I used for generating the plot:
spins <- runif(50, min = 0, max = 50)
Here is the code I used to generate the plot:
hist(spins)
Here is the results of the console:
> hist(spins)
Error in plot.new() : figure margins too large
Here are my questions:
How do I find out the current margins of this specific plot?
How do I modify the margins for this specific plot?
Is there a method to modify the margins for plots in general (e..g., Can I use 1 set of code to find the margins of the object and then use a second set of code to modify the margins so it will display in the plots area)?
Is there code I can use to automatically adjust the margins of the plots so that the desired plot displays every time?
The par function can be used to see the size of current margins and to set margin sizes (plus a whole bunch of other things).
Running par(c("mar", "mai")) will report the current margins (starting at bottom and going clockwise) in lines of text (mar) and inches (mai).
You can then set the margins using code like: par(mar=c(2,2,2,0)) or par(mai=rep(0.4, 4)).
But the problem is probably that you have made the plots pane in RStudio too small in at least one dimension, so when the hist function tries to create the plot there is not enough room for the plot and margin information. Try dragging the appropriate dividers within RStudio to make the plot panel larger then try your code again. Another option is to run the command dev.new() which will open a new window for the plots (using the default for your OS) and by default send the plot to that new window instead of the plot pane in RStudio.

Shrink viewing cell of R plots in jupyter

I am running R in jupyter, but I am running across some issues with plotting. Specifically whenever I plot the returned plotting window takes up the entire screen. I tried changing the dimension of the plot in R with par(pin=c(1,1)) etc... and it shrunk the actual image of the plot, but the cell width the images is in still takes up the entire screen. I can zoom out in my browser, but then I can't see my lines of code.
Code:
x <- runif(100)
hist(x)
Any suggestions on how to fix this would be appreciated. Thanks.
P.S. I would post an image, but I just created this account and need at least 10 rep points to post images
Answer:
I was able to change the options with the code below so my plots looked a little bit more reasonable
options(repr.plot.height=3)
options(repr.plot.width=3)

How to reset 'par' (pty='s') value in R

I was trying to plot two graphs simultaneously. I did it usingpar(mfrow=c(2,1) and reset the par to default with par(mfrow=c(1,1).
I was trying to make the size of dots in the scatter plot and ended in trouble. I mistakenly used par(mfrow=c(,1),pty='s') and my plot got re-sized instead of re-sizing the size of scatter dots.
Sorry since Im new to R; I want to reset the size to default value. ie, the value for pty='s' should go to default. How can I do that!! I tried with par(opar) and par(resetPar()) which I found from stackoverflow, but both returning could not find error.
Also, may I know how to increase the size of scatter dot(s)? Should I ask this as separate question?
Thank you for your help..
Before modifying the graphical parameters with par it may be useful to store the previous parameters:
old_par = par()
Then you'll be able to come back to previous settings by typing par(old_par). For your current problem, default value for pty is "m".
In any case, if you don't want to close your current graphical device to get the old_par parameter, you can still open a new one x11() then the par function will concern the new window, and then close it dev.off()

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

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

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)

Resources