r - 如何以适当的纵横比保存 ggplot2 图形?

标签 r ggplot2

我的问题是关于如何保存 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/

相关文章:

r - 在 Linux 上的 RStudio 中安装包时遇到问题

r - 获取 axis.text 和 axis.title 之间的边距值

r - 使用 ggplot 或 R 中的任何其他方法根据计数绘制线宽(大小)

r - ggplotly 错误顺序为 : argument 1 is not a vector

r - 如何使用 ggplot2 在 R 中绘制刺激时间直方图 (PSTH)

r - 在 ggproto 中,coord$transform 没有将某些列转换为 [0, 1]

r - 使用 choroplethr 包时修复了 Shiny 中 choropleth 的范围

R:在混合效应模型 (lme4) 中分析多重响应(即因变量)

r - n 个栅格层的堆栈{栅格}

r - 将离散标签添加到具有连续比例的 ggplot2 图