ggsave 忽略了我对高度和宽度的规范

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

我正在尝试为具有特定标准的出版物保存 ggplot 图。每当我使用 ggsave 设置高度、宽度、单位和 DPI 保存绘图时,我都会得到一个更大的图像。

我尝试了另一个数据集,即鸢尾花数据集,但仍然遇到同样的问题。下面是我的代码。

iris %>%
  group_by(Species) %>%
  summarise(Mean = mean(Sepal.Length)) %>%
  ggplot(aes(x = Species,y = Mean)) +
  geom_bar(stat = "identity",color = "black",fill = "lightgrey") 
ggsave("Example.jpeg",height = 3,width = 5,units = "in",dpi = 600)

这是我插入图片后在word中显示的图片大小。我预计原始尺寸为 3 英寸高、5 英寸宽。 Saved Graph in Word

r ggplot2 ms-word image-size ggsave
1个回答
0
投票

如果您在

ggplot2
中指定 600 dpi 的 3 x 5 英寸(高 x 宽)图像,则生成的 jpeg 文件将具有 1800x3000 像素。我使用 png 文件作为请求的输出图像对您的 reprex 进行了交叉验证(见下文)。

library (magick)

img <- image_read("Example.png")
image_attributes(img)                  

                   property                               value
1                date:create                     2024-03-08T10:48:06+00:00
2                date:modify                     2024-03-08T10:48:06+00:00
3             date:timestamp                     2024-03-08T10:48:16+00:00
4                   png:bKGD chunk was found (see Background color, above)
5    png:IHDR.bit-depth-orig                                             8
6         png:IHDR.bit_depth                                             8
7   png:IHDR.color-type-orig                                             2
8        png:IHDR.color_type                                 2 (Truecolor)
9  png:IHDR.interlace_method                            0 (Not interlaced)
10     png:IHDR.width,height                                    3000, 1800
11                  png:pHYs             x_res=23622, y_res=23622, units=1

然而,这是这里的重要部分,png 文件有 600dpi,而 jpeg 文件在我的机器上只有 96dpi。原因似乎是,根据

ggsave
文档, dpi 参数仅适用于“光栅输出类型”,显然还不支持 jpeg 文件。

关于期刊的输出,通常要求仅限于最低分辨率(通常在 300 dpi 左右)和某些支持的图像格式。因此,最简单的解决方法是查看他们是否也接受 png 文件,然后从那里开始,如果您愿意,可以使用 600dpi:

# Load packages
library(dplyr)
library(ggplot2)

# Set working directory
setwd ("yourwd")

# Image processing and saving using pipe
(
iris %>%
  group_by(Species) %>%
  summarise(Mean = mean(Sepal.Length)) %>%
  ggplot(aes(x = Species,y = Mean)) +
  geom_bar(stat = "identity", color = "black",fill = "lightgrey")
) %>%
ggsave("Example.png", ., height = 3, width = 5, units = "in", dpi=600, device = "png") 

确保不要监督最后一行中的

, .,

© www.soinside.com 2019 - 2024. All rights reserved.