ggplot2 plot scaling in R Markdown or Quarto

When you save ggplot2 plots, the output will be different depending on the image size. There is a nice blog post on plot scaling on the tidyverse blog. The final example they use is:

pngfile <- fs::path(knitr::fig_path(),  "downscaling.png")
ggsave(
  pngfile, 
  p, 
  device = agg_png, 
  width = 10, height = 6, units = "cm", res = 300,
  scaling = 0.5
)
knitr::include_graphics(pngfile)

They are saving the plot and then displaying that image with knitr::include_graphics(). If you are using R Markdown or Quarto, is there a more elegant way to display a scaled plot (something that does not involve saving the plot and then loading that image)?

I'm guessing it's question of setting the options of the code chunk that creates the plot, and that the details here should help:
https://r4ds.hadley.nz/quarto#sec-figures

You could set the fig-width, but you would have to define the width in an earlier chunk if you want it to be a variable. That's not particularly clean either.

To clarify on this, with any other method you would use, it would end up doing that. When setting fig-width or any other option, at some point R graphic device will be used to save an image file on disk, and then include it using the right syntax.

So doing ggsave + include_graphics() is exactly the same, just with more control for you on the two steps, which are usually done automatically internally by knitr.

Hope this helps understand

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.