change the font size and margin of R graph - r

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

Related

Control how much space legend.only takes from a raster plot in r

I am trying to simply plot a raster map and a legend barr, but i cannot seem to get it at the right distance from the raster. Is either over it or too far. Also, despite i indicate a fixed width and height to the SVG printing function, the final size does not look similar. Would it be a way to control the exact position of the legend barr when plotting legend.only=T? By the way, stack overflow does not allow me to upload an SVG image, so i am uploading a screen capture that looks similar.
here is how i see it in R
Here is how i get it from the file generated
Here is the script used to generate that image, region and range are polygons, and hill and tmax are rasters. The plotting in R works fine-I just want to know how avoid the changes in the image from the R window to the file. There seems to be something in the exporting function that is creating a high white space between the map and the barr, and it express only when exporting the graph.
svg(paste("/Users/",spp[i],"filename", ".svg",sep=""),
bg="transparent", width = 5,height=5)
plot(region)
plot(hill,col=grey(0:100/100), add=T, legend=F)
plot(range,add=T, border="turquoise")
plot(Tmaxc>tmaxsp,col=heat.colors(100),add=T,legend=F)
plot(Tmaxc>tmaxsp,col=heat.colors(100),legend.only=TRUE, horizontal = TRUE,
legend.args = list(text='Warming tolerance\u00B0C', side = 1, line = 2))
dev.off()

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.

Save Filled Area of Polygon in R

I am plotting polygon in R and saving it.Problem, I am facing is that the whole plot is saved as png file but I want to save only the filled area in the polygon.
Is there a way for that ?
x<-c(0.000000000,0.010986328,0.006351471,-0.004634857)
y<-c(0.000000000,0.007232612,0.012841203,0.006199415)
file_name = paste("~/Downloads/Plot", ".png", sep="")
png(file_name,width=1280,height = 720,units="px",res=200)
plot(x,y,axes=FALSE,ylab='',xlab='')+polygon(x,y,col="#FF0000FF")
dev.off()
If you're drawing a monofigure plot (which is the default), then I believe there are three possible sources of spacing that can cause a plot element to not extend to the edges of the graphics device:
1: data coordinate limits that are larger than the extent of the plot element.
2: "internal spacing", which is best thought of as an expansion of the plot area that sits inside the margins.
3: margins. This is normally where axes, ticks, tick labels, axis labels, titles, and sometimes legends are drawn.
All of these sources of spacing can be eliminated with the following customizations:
1: set the xlim and ylim graphics parameters to perfectly fit the target plot element.
2: set xaxs='i',yaxs='i', which can be done with either a preemptive par() call or on the initial plot() call.
3: zero the margins with mar=c(0,0,0,0). This must be done with par() prior to the initial plot() call.
Example:
## generate data
pts <- data.frame(x=c(0.2,0.4,0.9,0.7),y=c(0.5,0.4,0.5,0.6));
## precompute plot parameters
xlim <- range(pts$x);
ylim <- range(pts$y);
## draw plot
par(mar=c(0,0,0,0));
plot(NA,xlim=xlim,ylim=ylim,xaxs='i',yaxs='i',axes=F,ann=F);
points(pts$x,pts$y,pch=21L);
polygon(pts$x,pts$y,col='red',pch=21L);
Multifigure plots can incur one additional source of spacing, namely outer margins, but it looks like that doesn't concern you for this problem. In any case, I'm pretty sure outer margins always default to zero anyway.
See par() for the relevant documentation.
It looks like I misunderstood the question. What you want is a transparent background, which is different from simply fitting the image size to the plot element.
You can use the png() function to set the background to be transparent by passing bg='transparent', as explained on the documentation page.
For example, here's my fitted image saved with a transparent background:
Note that not all image viewers will correctly detect and/or clearly depict the transparency of the background. I would highly recommend GIMP, which is basically a free Photoshop knockoff, albeit markedly lighter in features. GIMP depicts transparent regions as a kind of checkerboard of grey squares, which looks like this:

Usage of layout in R

I'm trying to create this layout for this plot:
layout(matrix(c(1,1,1,1,1,1,
2,2,2,3,3,3,
2,2,2,3,3,3,
2,2,2,3,3,3), nrow=4,ncol=6,byrow = TRUE))
# Set up the top chart that keeps track of the current frame/iteration
# Dress it up a little just for fun
plot(-5, xlim = c(1997,2011), ylim = c(0, .3), xlab = "", ylab = "", main = "Time",axes=F)
abline(v=1995, lwd=5, col = rgb(0, 0, 255, 255, maxColorValue=255))
# Bring back the X axis
xticks <- 1997:2011
axis(side=1, at=xticks, labels=xticks)
# Plot
plot(1:100,1:100)
plot(1:100,1:100)
Obviously the last two plot aren't plot(1:100,1:100)in my real code, but I have a question on usage of layout. Why i get this error on the first plot?
Error in plot.new() : figure margins too large
I want the first picture to have a little height
It might sound silly, but the reason is indeed that the figure margins are too large!
Let me elaborate on this. In R, there are several kind of margins to let your pictures breath:
In your particular case, the margins are eating all the space available, as you try to cram too many figures in the same plot.
To solve this, I would advise to set all the margins to 0:
par(mai=c(0,0,0,0), oma=c(0,0,0,0), mar=c(0,0,0,0))
Which will likely result in your plot to at least be rendered. At the same time, all the subplots will be way too close to each other, so you then have to increase the margins little by little, with similar calls to par(...) until the results looks fine.
Hope this helps :)
The margins are measured in multiples of line-heights via the parameters par(mar), par(oma), and par(mai), as described in this passage in ?par
MAR
A numerical vector of the form c(bottom, left, top, right) which gives the number of lines of margin to be specified on the four sides of the plot. The default is c(5, 4, 4, 2) + 0.1.
There are two solutions, you can (a) reduce the margins by setting one of the previous 'par()' settings or (b) you can increase the size of the device, either by re-sizing the device using the mouse if it's a visible device, or if you are printing to PDF, for example, you can set the device size to be larger by setting height and width parameters when you set up the device, as in:
pdf( <<FileNameHere>> , width = par('din')[1],height = par('din')[2] )
I by setting width to par('din')[1] and height to par('din')[2], you get a PDF with the same dimensions as the current device, which lets you make adjustments to the visible device with the mouse. (This is handy for one-off plots and poor practice for a production environment)
If you do reduce the margins, I recommend not setting mar=c(0,0,0,0), as that will result in not having visible axis labels.

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