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

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)

Related

How can I adjust the position of tip labels relative to tree tips on a phylogenetic tree?

I am trying to create a figure of a map of a continuous trait onto a phylogenetic tree using the ape and phytools packages in R for a publication. An example code of what I am trying to produce is as follows:
library("ape")
library("phytools")
orig_tree<-rtree(n=350)
plot(orig_tree)
values<-data.frame("residuals"=runif(350,min=-1,max=1),row.names=orig_tree$tip.label)
values<-setNames(values$residuals,rownames(values))
residualsignalfit<-fastAnc(orig_tree,values,vars=TRUE,CI=TRUE)
obj<-contMap(orig_tree,values,plot=FALSE)
plot(obj,type="fan",fsize=.1,lwd=0.5)
The only difference is the terminal of the branches are all the same length because they are all living taxa, but this works well enough to illustrate the problem I am having. I have a large number of taxa in this tree, and as a result I have to shrink the text down fairly small using the fsize= argument to make them legible. However, as you can see from the example code, doing so causes the ends of each species name to be obscured by the outline for the phylogenetic tree. I have tried removing the outline but it makes the heatmap of the phylogeny very hard to read. I have been unable to find any way to reduce the thickness of the outline, it seems to be automatically generated.
I also tried adding the cex command to plot(obj...), but it has no effect on the produced tree at all.
What I am trying to figure out how to do is how to position the tip labels in order to make them more legible and not covered up by the outline for the tree. I cannot simply add a space in front of each terminal using the dplyr mutate function or something like that because the position of the taxon name is not always consistent, sometimes the left side of the name is attached to the tip and other times it is the right side. I have tried not plotting the data as a fan, but this ends up creating a figure with a huge amount of dead space due to the fact I have some very deep splits within the tree (basically plotting the figure as a right-facing tree results in half of the figure being dead space because my taxa diverged in the Mesozoic but only speciated after the K-T boundary).
Instead of shrinking the text down, you can scale the tree up. You can export the plot as image with a specific width and height. Setting both to 20 should make all tip labels legible.
Something like
setEPS()
postscript("output.eps", width = 20, height = 20)
plot(obj,type="fan",lwd=0.5)
dev.off()
This saves the plot to output.eps instead of showing it in the default viewer. So it is not restricted by the screen size. You still need to fiddle around with the best values of lwd and fsize, but in my experience it is much easier, when you have a big canvas.
Edit: Sorry, the unit of width and height is inches not pixels. So rather set it to 10 or 20.

R and pdf() make figures to breath

I am using the Gmisc package to plot some state diagrams. The package is great for this purspose but I am stuck with one visualization task when I try to build a very large diagram.
Even though it is hard to see in detail in a large screen all the information, it will be nice to be able to zoom in specific regions and see in more detail what is going on.
The gmisc package does not have parameters for scaling apart of setting width of a box.
The code that plots this diagram is just the following:
pdf(file="LargeFigure.pdf")
transitions$render()
dev.off()
Is it possible to inform the pdf device to take as much space is needed so the figure elements never overlap? Of course that will be a large figure where one will need to zoom in to see detail.
I would like to thank you in advance for your reply.
Regards
Alex
I think you can specify the width and height of your graphics region in the pdf file by specifying width and height options in pdf() function. An example
pdf(file="LargeFigure.pdf", width = 8, height = 8)
The default width and height in pdf() function are 7.

How do I make the table fit in the image created by tableGrob?

I am using tableGrob in R to create a .png image of a formatted table, for inclusion in a MS Word report. For small tables this works, but for larger ones they do not fit in the image. I haven't been able to find any parameters that allow me to either force it to fit automatically, or to manually control the height and width of the image window.
I would be very grateful if somebody could show me how to do this.
I am using R version 3.3.1, via Rstudio version 1.0.136, on Linux Mint on a 64-bit PC. R packages used include gridExtra, gridGraphics, gtable and png.
The table (tabsave) is a simple data frame with 34 rows and six columns, the first being chr and all the others num.
Here is what the output looks like. You can see how the table extends beyond both the upper and lower borders of the image:
Here is the relevant code
gtab<-tableGrob(tabsave,rows=NULL,cols=nm,theme = ttheme_default(base_size=10)) # gtab is the graphical version of the table, for printing
png('test.png')
grid.draw(gtab)
dev.off()
Thank you for any help you can provide.
The solution is to give width and height parameters to the png function. They both default to 480, in the default unit of pixels (px).
So I just changed
png('test.png')
to
png('test.png',height=1200)
I played around with the width and height parameters until it gave the coverage I needed.
When the plotting is to the interactive plot device, rather than to a file (ie not using a function like png) it's just a matter of first resizing the plot window so it's big enough.

Change plot size of pairs plot in R

I have this pairs plot
I want to make this plot bigger, but I don't know how.
I've tried
window.options(width = 800, height = 800)
But nothing changes.
Why?
That thing's huge. I would send it to a pdf.
> pdf(file = "yourPlots.pdf")
> plot(...) # your plot
> dev.off() # important!
Also, there is an answer to the window sizing issue in this post.
If your goal is to explore the pairwise relationships between your variables, you could consider using the shiny interface from the pairsD3 R package, which provides a way to interact with (potentially large) scatter plot matrices by selecting a few variables at a time.
An example with the iris data set:
install.packages("pairsD3")
require("pairsD3")
shinypairs(iris)
More reference here
I had the same problem with the pairs() function. Unfortunately, I couldn't find a direct answer to your question.
However, something that could help you is to plot a selected number of variables only. For this, you can either subset the default plot. Refer to this answer I received on a different question.
Alternatively, you can use the pairs2 function which I came across through this post.
To make the plot bigger, write it to a file. I found that a PDF file works well for this. If you use "?pdf", you will see that it comes with height and width options. For something this big, I suggest 6000 (pixels) for both the height and width. For example:
pdf("pairs.pdf", height=6000, width=6000)
pairs(my_data, cex=0.05)
dev.off()
The "cex=0.05" is to handle a second issue here: The points in the array of scatter plots are way too big. This will make them small enough to show the arrangements in the embedded scatter plots.
The labels not fitting into the diagonal boxes is resolved by the increased plot size. It could also be handled by changing the font size.

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