我的问题是关于如何保存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
Run Code Online (Sandbox Code Playgroud)
在下面的示例中,我将数据转换为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")
Run Code Online (Sandbox Code Playgroud)
但是,将尺寸设置为 4 x 4 将导致绘图侧面出现填充(白色边框)。因此,当将图形粘贴到 PowerPoint 演示文稿中时(例如),将出现这些白色边框。
ggsave(tf, p, width = 4, height = 4)
p
Run Code Online (Sandbox Code Playgroud)
您可以打开tf
并看到黑色区域周围的白色填充。我的问题是,如何找到绘图的正确纵横比,以便我可以提供适当的尺寸ggsave()
。
# Which dimensions to use to respect the aspect ratio of the map?
# ggsave(tf, p, width = xxx, height = yyy)
Run Code Online (Sandbox Code Playgroud)
由reprex 包(v0.3.0)于 2019-11-28 创建
归档时间: |
|
查看次数: |
3269 次 |
最近记录: |