我的问题是关于如何保存 ggplot2
图关于
纵横比。如果我制作一个简单的图形并设置绘图的尺寸
与 ggsave()
,绘图将占据保存文件的整个区域。
library(ggplot2)
library(sf)
#> Linking to GEOS 3.7.1, GDAL 2.4.2, PROJ 5.2.0
#> WARNING: different compile-time and runtime versions for GEOS found:
#> Linked against: 3.7.1-CAPI-1.11.1 27a5e771 compiled against: 3.7.0-CAPI-1.11.0
#> It is probably a good idea to reinstall sf, and maybe rgeos and rgdal too
df <- data.frame(
longitude = -47,
latitude = 45
)
p <- ggplot(df, aes(x = longitude, y = latitude)) +
geom_point() +
theme(
plot.background = element_rect(fill = "black")
)
tf <- tempfile(fileext = ".png")
ggsave(tf, p, width = 4, height = 4)
p
在以下示例中,我将数据转换为
sf
对象和情节它使用
geom_sf()
这导致情节具有一定的纵横比匹配所选的投影。
df <- st_as_sf(df, coords = c("longitude", "latitude"), crs = 4326)
p <- ggplot(df) +
geom_sf() +
theme(
plot.background = element_rect(fill = "black")
)
tf <- tempfile(fileext = ".png")
但是,将尺寸设置为 4 x 4 会导致填充(白色边框)出现在
情节的一侧。因此,当
图形被粘贴到 PowerPoint 演示文稿中(例如)。
ggsave(tf, p, width = 4, height = 4)
p
您可以打开
tf
并看到黑色区域周围的白色填充。我的问题是,如何找到正确的绘图纵横比,以便为
ggsave()
提供适当的尺寸.# Which dimensions to use to respect the aspect ratio of the map?
# ggsave(tf, p, width = xxx, height = yyy)
创建于 2019-11-28 由 reprex package (v0.3.0)
最佳答案
这是我删除 ggplot2 图形周围边框的解决方案:https://www.pmassicotte.com/post/removing-borders-around-ggplot2-graphs/
关于r - 如何以适当的纵横比保存 ggplot2 图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59089928/