在 RStudio 查看器窗格中以正确的尺寸显示 ggplot .png

displaying ggplot .png in RStudio viewer pane with correct dimensions

我正在编写一个函数来将绘图保存到 R 临时目录,然后在查看器窗格中显示它。 (部分基于 的最后一段。)如果我将绘图另存为 .svg,它会根据当前窗格尺寸以恰到好处的大小保存并显示在查看器窗格中:

library(ggplot2)
library(grDevices)

plt <- ggplot(iris) +
  geom_point(aes(Sepal.Width, Sepal.Length))

dev.size()
# 5.250000 2.927083

plt_path <- tempfile(fileext = ".svg")
ggsave(plt_path, plt)
# Saving 5.25 x 2.93 in image

viewer <- getOption("viewer")
viewer(plt_path)

但是,如果我将其另存为 .png,则显示的图像太大了。 (请注意,ggsave() 仍然报告将其保存为正确的大小。)

plt_path <- tempfile(fileext = ".png")
ggsave(plt_path, plt)
# Saving 5.25 x 2.93 in image

viewer <- getOption("viewer")
viewer(plt_path)

使用 type = "cairo" 问题仍然存在,即使我手动设置 ggsave 尺寸:

dims <- dev.size(units = "in")
plt_path <- tempfile(fileext = ".png")
ggsave(plt_path, plt, width = dims[[1]], height = dims[[2]], units = "in")

如何保存和显示 .png 图像以匹配查看器窗格的尺寸?

分辨率需要与您的设备相匹配。 ggsave 中的默认 dpi 是 300,但显示器通常是 96 dpi:

dims <- dev.size(units = "in")
plt_path <- tempfile(fileext = ".png")
ggsave(plt_path, plt, width = dims[[1]], height = dims[[2]], units = "in",
       dpi = 96)

viewer <- getOption("viewer")
viewer(plt_path)