7

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.

enter image description hereenter image description here

lxcfuji
  • 329
  • 1
  • 4
  • 15

3 Answers3

1

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()
Jthorpe
  • 9,756
  • 2
  • 49
  • 64
  • 1
    could you explain how this solves the issue? I just attempted to implement your code and I am still getting cut off legends. –  Mar 26 '19 at 15:43
  • they're using the R viewer to set the dimensions and then save the pdf with the same ones. par('din') is read-only and so is getting the dimensions from dev.size('in') – MilleCodex May 30 '22 at 22:38
1

Save it using png() or tiff():

tiff("filename",

<code for plot>,
height=5,width=7)
dev.off()
brucezepplin
  • 9,202
  • 26
  • 76
  • 129
0

After plotting, try

% your code…

dev.copy(pdf, 'yourfile.pdf')
dev.off()

From https://statistics.berkeley.edu/computing/saving-plots-r

Matthias
  • 737
  • 8
  • 14