准确设置ggsave的大小

问题描述 投票:0回答:2

R
问题。

我对

width
height
dpi
unit
感到非常困惑。

为什么以下两个尺寸不同?

ggsave(filename = "foo.png",ggplot(mtcars, aes(x=wt, y=mpg)) +
    geom_point(size=2, shape=23),width = 5, height = 4, dpi = 300, units = "in", device='png')

ggsave(filename = "foo.png",ggplot(mtcars, aes(x=wt, y=mpg)) +
           geom_point(size=2, shape=23),width = 5, height = 4, dpi = 72, units = "in", device='png')

我将两张图片的尺寸都设置为5(英寸)* 4(英寸)。但为什么当我改变

dpi
时,大小会改变呢?

如何理解

height
width
unit
dpi
之间的关系?

或者这四个参数如何翻译成像素单位,这样更容易理解?

r ggplot2 dpi
2个回答
61
投票

要了解 DPI 为何如此重要,请考虑以下两张图:

ggsave(filename = "foo300.png", ggplot(mtcars, aes(x=wt, y=mpg)) +
           geom_point(size=2, shape=23) + theme_bw(base_size = 10),
       width = 5, height = 4, dpi = 300, units = "in", device='png')
ggsave(filename = "foo150.png", ggplot(mtcars, aes(x=wt, y=mpg)) +
           geom_point(size=2, shape=23) + theme_bw(base_size = 10),
       width = 10, height = 8, dpi = 150, units = "in", device='png')

生成的文件具有相同的像素尺寸,但每个文件的字体大小不同。如果您将它们放置在与

ggsave()
调用具有相同物理大小的页面上,则字体大小将是正确的(即
ggsave()
调用中的 10)。但是,如果您以错误的物理尺寸将它们放在页面上,则字体大小将不是 10。要在增加 DPI 的同时保持相同的物理尺寸和字体大小,您必须增加图像中的像素数。


8
投票

您给出的两个示例具有相同的图像“缩放”但不同的“图像质量”,如果您将保存的png拉入

.docx
文件中,将它们拖动到相同的大小,您将看到它们是相同的图像,只是不同的“图像质量”。因此,这样,我们将
width and height
理解为图像“缩放”,将
dpi
理解为“图像质量”。

如果您想保存在预览窗口中看到的图形,这将是最佳实践:

  1. 首先是ggplot
 ggplot(mtcars, aes(x=wt, y=mpg)) +
           geom_point(size=2, shape=23)
  1. 检查Rstudio Plots窗口中的图形,如果不满意,单击缩放,将弹出窗口拖动到您想要的大小

  2. 右键单击图形并选择检查元素

然后你会看到这条线

<img id="plot" width="100%" height="100%" src="plot_zoom_png?width=214&amp;height=151">

上面的行表明您的最佳宽度是 2.14,最佳高度是 1.51

  1. ggsave() 你刚刚看到的内容
ggsave(filename = "foo3.png",width = 2.14, height = 1.51, dpi = 300)
# set the dpi as journal requirement, now the dpi only changes image quality, not image content, default unit is 'in' inch

如果您想塑造自己的身材以满足期刊的需要,这将是最佳实践:

  1. 从日志中获取参数,例如宽度=180mm,高度=185mm,遵循Nature链接

  2. 使用该参数创建一个新的图形窗口

# you only need noRStudioGD=TRUE if using Rstudio
dev.new(width = 90, height = 180, unit = "mm",noRStudioGD=TRUE)
#note that a new window will appear in your task bar
  1. plot() 或 ggplot() 并在该窗口中预览图形

  2. ggsave()你所看到的

ggsave(filename = "foo3.png",width = 90, height = 180, unit = "mm", dpi = 300)
© www.soinside.com 2019 - 2024. All rights reserved.