Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does R re-size everything in the plot but not the text when exported?

Tags:

plot

r

pdf

Whenever I try to export R plot, either with RStudio with with pdf(), I find that all the elements are re-sized accordingly but not the text. This can lead to titles being cut off even.

Try resize this plot in Rstudio (or use pdf("plot.pdf", width, height) in base R):

ggplot(data=data.frame(x=rnorm(100), y=rnorm(100)), aes(x, y)) +
  geom_point() +
  geom_text(aes(label=rep("a", 100))) +
  labs(y="Title that is very loooooooooooooooooooooooooooooooooooooooong")

When width x height is 5 x 5, the text is oversized and the title is cut-off. But as 10 x 10, everything fits in.

So it seems like the text remains at a constant "size" no matter what I specify for the size of the plot. Is this a correct understanding of how R export graphics?

If that's the case, what do you typically do to make sure that the text in the exported graphics fit in?

like image 353
Heisenberg Avatar asked May 26 '15 19:05

Heisenberg


People also ask

Can you export all plots in R?

You can export your plots in many different formats but the most common are, pdf, png, jpeg and tiff. By default, R (and therefore RStudio) will direct any plot you create to the plot window. To save your plot to an external file you first need to redirect your plot to a different graphics device.


1 Answers

I finally see the intuitiveness behind this behavior. When I posted the question, I expect R to resize all the elements inside the graph when I resize the graph.

However, in fact, the size of ALL elements are fixed, including text, line, tick mark, etc., and re-sizing the graph only changes the size of the graph while maintaining the relative position of the elements.

To see this, run pdf("small.pdf",5,5); plot(1,1); dev.off() and pdf("large.pdf",10,10); plot(1,1); dev.off(). Then, if you display the two graphs, zoom so that the physical size on screen is 5x5 and 10x10, the element sizes should be the same between the two plots.

So the best practice is probably (please share your practice):

  1. when plotting specify elements' sizes that make sense relative to one another,
  2. when exporting, choose a plot size that everything fits in,
  3. import into latex using \includegraphics[width=\textwidth, height=\textheight,keepaspectratio]
like image 73
Heisenberg Avatar answered Nov 15 '22 17:11

Heisenberg