plot got cut off after saving to file - r

My fig has a large legend outside the plot. 6 lines with long description When I save it, the legend doesn't show up. I adjusted par, but it still doesn't work.
legend("topright", inset=c(-0.6,0),xpd=TRUE,cex=0.8,
+legend=c("A_all peaks","B_ from all peaks","C_from all peaks","A_from unique peaks",
+"B_from unique peaks","C_from unique peaks",
+"A_from overlap peaks","B_from overlap peaks","C_from overlap peaks"),
+col=c("green","red","blue","lightgreen","pink","lightblue","darkgreen","darkred","steelblue"),
+pch=c(20,20,20,20,20,20,20,20,20),bty="n")
> par()$oma
[1] 2 2 2 2
> par()$mar
[1] 5.1 4.1 4.1 8.0
When save it with long width(tried 800,1000 pixel), no legend showed. But when as as short width(), part of legend shows. This is really confused me.first graph is 500*333, second graph is 500*800.

Not sure how you're saving the plot to file, but my usual routine is to make a pretty plot in R by the usual means:
plot(blah,blah,blah)
legend(blah,blah,blah)
and then once I'm happy with the appearance of the figure the R console, I use pdf() or one of it's cousins(jpeg(),tiff(), etc.) to save it to file, making sure to set the width and height parameters like so:
# set up plotting device
pdf( {{FileName}},
width = par('din')[1],
height = par('din')[2])
plot(blah,blah,blah)
legend(blah,blah,blah)
# disconnect the plotting device
dev.off()

Save it using png() or tiff():
tiff("filename",
<code for plot>,
height=5,width=7)
dev.off()

After plotting, try
% your code…
dev.copy(pdf, 'yourfile.pdf')
dev.off()
From https://statistics.berkeley.edu/computing/saving-plots-r

Related

How to have title in R Vennerable Venn Diagram?

I cannot find anything in documentation here.
Code
library("Vennerable")
data(StemCell)
Vstem <- Venn(StemCell)
Vstem3 <- Vstem[, c("OCT4", "SOX2", "NANOG")]
tl <- "masi"
plot(Vstem3, doWeights = TRUE, type = "circles")
Tried unsuccessfully
plot(..., main = tl)
plot(..., title = tl)
plot(...); title(tl)
plt <- plot(...); title(plt, tl)
Fig. 1 Wrong output without title
R: 3.3.1
OS: Debian 8.5
user20650 answer in comments summarised here. Try (1-2) and choose what fits best.
The plot method is based on the grid package so the normal base R plot approaches to add a title won't work. Looking at the arguments of args(Vennerable:::plotVenn), there doesn't seem a way to add a title and unhelpfully the plots do not return a grid object. So you can just draw a title on the plot window with the following
grid.text("masi", y=0.9, gp=gpar(col="red", cex=2))
As an alternative method, you could grab the grob and then use grid.arrange to plot the title
gridExtra::grid.arrange(grid::grid.grabExpr(plot(Vstem3, doWeights = TRUE,
type = "circles")), top="masi")
The grid.arrange way adds the title as a separate grob, and then they are arranged in two rows. So when resizing the graphics window, it still appears above the plot. This won't be true when drawing straight on the window (as in the first version).
Note: you do not need to use gridExtra, you could do this in grid.
Fig. 1 Output from (1),
Fig. 2 Output from (2)
I think (1) could be better with more adjustments, but now (2) is better.

When creating PNG in R, the legend is cut off

I wrote some R code 4 years ago and haven't use R since. I am struggling to get this working again:
radio_count = data[c("a","ac","an","bn","g")]
# Create a new PNG file
png(filename=png_file, width=850, height=600, bg="white") #,antialias="cleartype")
# Expand right side of clipping rect to make room for the legend
par(xpd=T, mar=par()$mar+c(5,0,0,5),las=3)
# actually plot the bar graphs, with title
barplot( t(radio_count), main=gr_title, ylab="# of clients",col=barcolors,names.arg=data[,1],ylim=c(0,150) )
legend(36.5,100,chartlegend,cex=0.8,fill=barcolors)
grid(nx= 0, ny = NULL, col="gray60",equilogs = TRUE)
dev.off()
With 850x600, the legend is slightly clipped - meaning it only shows about 80% of the legend with the right most portion being cut off.
I need to use 1920x1080 now and the legend is not on the PNG at all.
What do I need to adjust to get the legend on the screen?
This did the trick for me:
barplot( t(radio_count), main=gr_title, ylab="# of clients", col=barcolors,
cex.main=2.2, cex.names=1.65, cex.axis=1.65, cex.lab=1.4,
names.arg=data[,1], ylim=c(0,150) )
Also note that ylim=c(0,150) tells R to make the Y axis range from 0 to 150.

Saving a plot in 'R' in 'eps' or 'pdf' format via 'rgl.postscript' (why color is changed?)

I am trying to run this code in "R" in order to plot a density function kernel smoothing and then save the plot as an "eps" file:
library(ks)
library(rgl)
kern <- read.table(file.choose(), sep=",")
hat <- kde(kern)
plot(hat, drawpoints=TRUE, xlab = "x", ylab= "y", zlab= "z")
rgl.postscript("plot1.eps","eps",drawText=TRUE)
The problem is that when I save the plot in eps format, it just shows the plot in one color (yellow) instead of a rage of colors (yellow, orange, red...) which shows different densities... (The plot in R is fine but when I save it as eps, the color is changed)
Do you know what is the problem with this code, or could you introduce me any other function that can save the plot that I generated in R as pdf or eps? (since it's an interactive RGL plot, I cannot use pdf() function. Also I tried rgl.snapshot, but every time it crashes and seems doesn't work...Following is part of my data: (x,y,z locations of points)
163.911642 248.952593 1.428709101
163.930843 249.077891 0.425459167
163.773321 249.288606 2.319076487
162.256416 246.990378 2.658388572
165.300014 247.950225 2.151660061
164.922344 249.017609 0.848590512
163.909127 248.881616 2.466267052
163.91322 249.118025 0.576787314
164.658937 249.547614 1.25279399
378.710211 132.601628 0.109772592
379.402818 132.858292 0.756297975
379.91023 132.912093 0.436653026
379.453418 132.815987 0.349591828
379.46519 132.694182 0.648543879
378.01787 132.615919 0.245000332
56.816299 27.469173 2.587220473
56.958051 27.103275 3.64182119
55.763676 26.59811 2.957732481
55.299606 26.054619 0.924209356
56.505342 27.671528 4.191381437
... ... ...
295.366938 24.360195 2.779443783
291.361501 23.21226 0.975021774
292.26276 22.053726 1.092983265
159.333055 41.087969 0.185656788
154.424175 37.83109 3.327367998
158.723404 40.487105 0.563578901
157.204282 41.678425 1.464830439
What I understand from your question is that the colours become different from what is displayed in X11 (assuming Linux environment) and the postscript (or eps) file.
Gnuplot colours are set for different terminal i.e. colours admissible to different terminals. So, the colours displayed in X11 (the default display term in Linux or Mac OSX) may be different in postscript.
To examine the permissible colours in a particular terminal is the Gnuplot command test. So, inside Gnuplot, the following set of command will produce a test.eps which when displayed will give you an idea what real colours you will be reproducing.
gnuplot> set term post colour eps
gnuplot> se out 'test.eps'
gnuplot> test
gnuplot> se te X11
Look at the test.eps file for true colour reproduction.

small plot with no margins - border with line width (lwd) equal to 1 not visible

I've been trying to make some very tiny line graphs using base plotting functions, but am coming unstuck when trying to add a thin border.
This is via RGui on Windows 7, saving a png from the plot window.
Here's my code:
dev.new(width=1.3,height=0.3)
par(mar=c(0,0,0,0))
set.seed(13)
x <- 1:10
y <- runif(10)
plot(x,y,type="n",xaxs="i",yaxs="i",ylim=c(0,1))
polygon( c(1,x,max(x),0), c(0,y,0,0), col="lightblue", border=NA)
lines(x,y,lwd=1)
Everything is fine until I try to add a box with a line width of 1, giving:
box(lwd=1)
Now I can solve this by increasing the line width to 2, but this seems a bit of a hack.
box(lwd=2)
Using rect like rect(1,0,10,1) doesn't seem to give me an appropriate solution either, with the bottom and right borders not being visible.
Have you considered giving mar a small non-zero value:
dev.new(width=0.3,height=0.3)
par(mar=c(0.01,0.01,0.01,0.01))
set.seed(13)
x <- 1:10
y <- runif(10)
plot(x,y,type="n",xaxs="i",yaxs="i",ylim=c(0,1))
polygon( c(1,x,max(x),0), c(0,y,0,0), col="lightblue", border=NA)
lines(x,y,lwd=1)
box(lwd=1)
I admit I haven't quite figured out what the end-game might be, but when I do an interactive "stretch" of that very small screen-object, it does result in an all-around border.
I do recognize that I am on a Mac and saving this to a pdf file and converting it to a png file for SO-inclusion may not be precisely reproducible on a Linux or Windows device.
Another solution base in grid and gridBase package. The idea is to replace the box by grid.rect.
Use gridBase to get the base viewport
Introduce some offset (viewport y ) to show the bottom line
Reduce the width of the viewport to show the right line.
Here my code:
library(gridBase)
sp <- baseViewports()
vp <- sp$plot
vp$width <- unit(0.999,'npc')
vp$y <- unit(0.001,'npc')
pushViewport(vp)
grid.rect(gp=gpar(fill=NA))
upViewport(1)
EDIT thanks to #baptiste, you can simply get the same result using only grid.rect:
library(grid)
grid.rect(width = unit(0.999,'npc'),
y = unit(0.5001, "npc"),
gp=gpar(fill=NA))
To answer my own question thanks to #baptiste's tip-off, this is a device dependent issue due to RGui. If the image is saved directly out to file using png everything works as intended. E.g.:
dev.new(width=1.3,height=0.3)
# repeat from here onwards only for png call below
par(mar=c(0,0,0,0))
set.seed(13)
x <- 1:10
y <- runif(10)
plot(x,y,type="n",xaxs="i",yaxs="i",ylim=c(0,1),bty="n")
polygon( c(1,x,max(x),0), c(0,y,0,0), col="lightblue", border=NA)
lines(x,y,lwd=1)
box(lwd=1)
Saving out to png from the "R Graphics" window gives my original stuffed up image:
Going directly to file using png like:
png("textbox_direct.png",width=116,height=27)
# take code block from above
dev.off()
...gives the correct result:

r multiple graphs on a single jpeg

I have run into the following problem and I would appreciate if someone could give me some input.
I would like to export multiple figures to a single jpeg file. I first create a graphics lattice and then I export. My main issue is that it works with the pdf and not the jpeg. Any ideas?
Thank you
#set the windows of the frames
par(mfcol=c(3,2))
#create the jpeg file
jpeg(filename=names(a1),".jpg",sep=""),
quality=100,
width=1024,
height=768)
#plot 1
plot(a1,b1)
#plot 2
plot(a1,b2)
#plot 3
plot(a1,b3)
#plot 4
plot(a2, c1)
#plot 5
plot(a2, c2)
#plot 6
plot(a2, c3)
#dev.off shuts down the specified (by default the current) graphical device
#here it passes the picture to the file
dev.off()
It is not clear whether you want multiple 1024x768 images in a single jpeg file - which doesn't make sense - are whether you want a single jpeg image containing the 6 plots.
As I said, JPEGs are not a multi-page format, unlike a PDF. Hence you can get R to export to multiple JPEG files but not have all the separate figures in one JPEG.
R's devices allow for wildcards in the filenames, so if you want the six plots exported to files foo001.jpeg, foo002.jpeg, foo00x.jpeg then you can use the following
jpeg(filename = "foo%03d.jpeg", ....)
.... # plotting commands here
dev.off()
What happens if you do multiple plots without the wildcard/placeholder is document in say ?jpeg:
If you plot more than one page on one of these devices and do not
include something like ‘%d’ for the sequence number in ‘file’, the
file will contain the last page plotted.
Devices that handle multiple pages because the underlying file format allows it can take multiple plots into the single file as there is makes sense, e.g. pdf() and postscript(). Those devices have argument onefile which can be used to indicate if multiple plots in a single file are required.
However, the par(mfcol=c(3,2)) makes me think you want a 3x2 set of plots in the same device region. That is allowed, but you need to call par() after you open the jpeg() device, not before. What your code, as shown, does is split the active device into 3x2 plotting regions and then opens a new device which picks up the default parameters, not the ones you set on the device active before you called jpeg(). This is illustrated below:
> plot(1:10)
> dev.cur()
X11cairo
2
> op <- par(mfrow = c(3,2))
> jpeg("~/foo.jpg")
> par("mfrow")
[1] 1 1
> dev.off()
X11cairo
2
> par("mfrow")
[1] 3 2
Hence you want perhaps wanted something like:
jpeg(filename=names(a1),".jpg",sep=""), quality=100,
width=1024, height=768)
op <- par(mfcol=c(3,2))
#plot 1
plot(a1,b1)
#plot 2
plot(a1,b2)
#plot 3
plot(a1,b3)
#plot 4
plot(a2, c1)
#plot 5
plot(a2, c2)
#plot 6
plot(a2, c3)
par(op)
dev.off()
?
The corrected code
#data
a1<-seq(1,20,by=1)
b1<-seq(31,50,by=1)
b2<-seq(51,70,by=1)
b3<-seq(71,90,by=1)
#create the jpeg file
jpeg(filename="a.jpg",
quality=100,
width=1024,
height=768)
#set the create the frames
par(mfcol=c(3,1))
#plot the graphs
plot(a1,b1)
plot(a1,b2)
plot(a1,b3)
#par(op)
#dev.off shuts down the specified (by default the current) graphical device
#here it passes the picture to the file
dev.off()

Resources