aspect ration of ggplot2 plot [duplicate] - r

This question already has answers here:
Save plot with a given aspect ratio
(5 answers)
Closed 6 years ago.
I used coord_fixed to change the aspect ratio of my plot. Unfortunately, as you can see below, the size of the window of the plot is still square, resulting in large amounts of white space above and below my plot. How do I change the size of the window to, say "wrap the content" that's inside of it?

Ok, with the help of Roland, I've figured it out. ggplot2 plots are always displayed in a device and that's where the height has to be set. For instance, I'm on linux and if I want to display a plot on screen, it gets done with x11(). In the R console, simply doing
> x11(width = 7, height = 3.5)
will result in a window with a dimension of 7 inches by 3.5 inches. Subsequent calls to ggplot2 will automatically use this window. The standard size is 7 inches by 7 inches and in my case resulted in the large areas of white space above and below the plot, which of course are smaller when the window has a height of 3.5 inches.
The next step, was getting the height right when rmarkdown uses the png device. This is actually a knitr issue and can be specified in the chunk options of the code block where the plot gets generated.
Here's the relevant code for my case
```{R, fig.width = 7, fig.height = 3.5}
# ggplot2 code goes here
```

Related

How to output always the same size (width/height) graph in R?

When I output the graph in R, the size (width and length) is always changing. So whenever I output graphs, I change the size by myself.
For example, I need a consistent graph size to insert into my document, but sometimes the default value of width and height is not the same when I try to export, particularly on different PC. How can I fix W:500. H:400 graph size all the time?
Many thanks!!
In order to get consistency, you should set the size of the graphics device yourself before plotting. For example, in Windows, you can use
windows(width=5.5, height=5, title="Controlled Size")
## NOW make your plot
to get a window that is always 5.5 inches wide by 5 inches high.
Other devices use minor variations for setting the size. You can check out other devices by looking at the help page help(Devices)
For example, bmp, jpeg, png and tiff allow you to set the number of pixels, not just the number of inches.

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

ggplot2 grid.export plot size SVG

How can I specify the width and height of the final SVG when I do:
print(plot)
saveXML(grid.export()$svg)
I'm producing plots for a web application in SVG. I was using ggplot2 and saving the plot using ggsave which allowed me to specify size in inches for width and height. I worked great. I now needed to perform annotations on the SVG and it seemed that ggsave did not work, so I'm forced to use the grid.export approach presented above. The only aspect I seem to have control is the resolution, which allows me to make plots smaller. However, while ggsave made all the text and point size scale to a bigger size, the grid.export approach changing the resolution can make the plot smaller, but just by makes everything smaller so the plot reads worse.
For instance, setting width and height to 3
ggsave version:
grid.export version:
What I managed to do is define a new base_size on the theme to compensate the resolution scaling:
base.size = 10 * (7/size)
resolution = 72 * (size/7)
if (length(plot$theme) == 0) plot <- plot + theme_gdocs();
plot$theme$text$size = base.size
mysvg <- grid.export(res=resolution)

font size confusion in ggplot2

I'm working on a manuscript for a journal and the requirement is font size 10 for graphs. I tried this in R with ggplot2 with a setting like this:
p<-qplot(...)+theme_bw()
ggsave(filename="plot.pdf",plot=p,width=8,height=8,scale=1.3)
The x and y axis text in the figure looks really small.. I checked the R code for theme_bw() and i think the axis text font is the default 12 times 0.8, so roughly font 10. Is font size 10 in ggplot is really equal to font size 10 in Word or other context?
I've read this post: ggplot2 - The unit of size
And I'm also confused by whether the font size 100 used in the above post is actually 100 or 100/0.35277... which one is it?
Lastly, when I put the figure in Illustrator along with others in a panel, the resulting axis font looks pretty small. I kinda feel it's not font size 10 but it was generated with font size 10 specification in R.. Not sure if I should use a larger font to make it look bigger.
Too long for a comment. I'm not sure I understand your question completely, so if this isn't helpful let me know and I'll delete it.
First of all width and height in ggsave(...) refers to the width and height of the image. The default units are inches, but this can be changed via the units=... argument. So in your code the image will be 8" by 8". If you view this in Acrobat Reader at 100%, the font sizes will be whatever you've set them to in ggplot (see below). But if you create an 8 X 8 image (which is pretty big) and then scale it down for inclusion in a paper, everything will get smaller. Said another way, if the image in you paper is physically 3 X 5 (as an example), then the call to gggsave(...) should reflect that.
Second, in ggplot you can set the size of the axis text (the tick mark labels), and the axis title (the axis label) separately. The default in theme_bw() is axis.title=12pt and axis.text=0.8*12pt. So if you want both the axis label and the tick mark labels to be 10pt, you need to specify:
theme_bw() +
theme(axis.text=element_text(size=10),axis.title=element_text(size=10))

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