导出 ggplot 时保持比例

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

我在导出 ggplot 图形并保持正确的尺寸时遇到问题。单个元素总是显得臃肿,并且物理尺寸与提供的定义不匹配或变得更大。 这个问题在下面的例子中得到了最好的解释,其中已经包含了我经过大量搜索后找到的建议。

library(ggplot2)
# example data
y <- rnorm(5, mean = 3)
barfill <- c("Elefants", "Shoes", "Soup", "Elefants", "Soup")
# plot
p <- ggplot() + 
  geom_col(aes(x = 1:5, y = y, fill = barfill)) + 
  geom_text(aes(x = 1:5, y = y-0.5, label = c("there", "are", "five", "columns", "here"))) +
  labs(title = "A random figure", subtitle = "with a couple of elements")


# scaling solutions for exporting the plot

# 1 - standard export  # appears crowded
ggsave(filename = "testbars.jpg", plot = p, width = 75, height = 75, units = "mm", dpi = 300)

# 2 - adjusting text size  # still out of proportions
p2 <- p + theme(text = element_text(size = 6))   # does not scale geom_text
### p2 +  update_geom_defaults("text", list(size = 4))  # this would scale geom_text, but changes defaults and thereby messes up other figures
ggsave(filename = "testbars_textscaled.jpg", plot = p2, width = 75, height = 75, units = "mm", dpi = 300)  

# 3 - scale entire image  # looks good, but image dimensions grow
ggsave(filename = "testbars_scaled.jpg", plot = p, width = 75, height = 75, units = "mm", dpi = 300, scale = 2.2)  

第一个图像看起来好像毕加索会写一份出版物,而第二个图像已经稍微好一些,尽管 geom_text 没有缩放,其他元素(例如图例框)也没有缩放。使用

update_geom_defaults("text", list(size = 5))
解决了 geom_text 问题,但代价是其他图受到更改的整体默认值的影响(这对我来说不是一个选项)。 使用 ggsave 的缩放函数的第三个解决方案(testbars_scaled.jpg)提供了我想要的图形。然而,该功能可能通过增加单个元素之间的距离来极大地扩展物理尺寸。当稍后插入文本时,手动将数字缩小到所需的大小似乎不是正确的方法。 图像尺寸也是以前方法中的一个问题,即使正确提供了尺寸和单位,物理尺寸总是比 ggsave 中定义的大(?)。

有没有办法实现第三种方法的效果,同时获取指定尺寸的图像,或者以其他方式导出具有适当比例的图形? 由于必须创建数百个标准化图形,因此理想的解决方案不应涉及使用光标手动调整图像尺寸,而应适合自动化。

感谢和问候!

r ggplot2 figure ggsave proportions
1个回答
0
投票

谢谢大家的热心解答!

这是迄今为止为我提供的最佳结果: 第一条评论中发布的有用链接引用了另一篇有用的文章:https://www.tidyverse.org/blog/2020/08/take-control-of-plot-scaling/

显然,有人面临同样的问题,并对 ragg 库实现了缩放解决方案,这似乎可以在不增加图像尺寸的情况下缩放所有内容。

library(ragg)
agg_jpeg(filename = "ragg.jpg", width = 75, height = 75, units = "mm", res = 300, scaling = 0.5)
plot(p)
invisible(dev.off())

生成的图形与未缩放的图具有相同的尺寸,但其元素的大小和比例正确。 链接的文章还提到,也可以通过更改设备通过 ggsave 访问此解决方案:

ggsave(device = agg_jpeg, [...])
然而,这(至少对我来说)会随着图像尺寸的增加而回归到初始的 ggsave 缩放。 幸运的是,到目前为止 agg_jpeg 方法似乎为我解决了这个问题。

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