如何以适当的宽高比保存ggplot2图形? [英] How to save a ggplot2 graphic with the proper aspect ratio?

查看:615
本文介绍了如何以适当的宽高比保存ggplot2图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于如何保存ggplot2图 长宽比.如果我制作一个简单的图形并设置图的尺寸 使用ggsave(),绘图将占据已保存文件的整个区域.

My question is about how to save a ggplot2 graph in respect with the aspect ratio. If I make a simple graphic and set the dimension of the plot with ggsave(), the plot will occupy the entire area of the saved file.

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()可以使绘图具有一定的宽高比 匹配所选的投影.

In the following example, I transform the data into an sf object and plot it using geom_sf() This cause the plot to have a certain aspect ratio to match the chosen projection.

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演示文稿中(例如).

However, setting the dimensions to 4 x 4 will cause paddings (white borders) to appear on the side of the plot. Hence, these white borders will be present when the graph is pasted into a PowerPoint presentation (for example).

ggsave(tf, p, width = 4, height = 4)

p

您可以打开tf并在黑色区域周围看到白色填充. 我的问题是,如何找到绘图的正确长宽比,以便为ggsave()提供适当的尺寸.

You can open tf and see the white padding around the black area. My question is about, how can I find the correct aspect ratio of the plot so I can provide appropriate dimensions to ggsave().

# Which dimensions to use to respect the aspect ratio of the map? 
# ggsave(tf, p, width = xxx, height = yyy) 

reprex软件包(v0.3.0)于2019-11-28创建 sup>

Created on 2019-11-28 by the reprex package (v0.3.0)

推荐答案

这是我的解决方案,用于删除ggplot2图形周围的边框: https://www.pmassicotte.com/post/removing-borders-around-ggplot2-graphs/

Here is my solution to remove borders around ggplot2 graphs: https://www.pmassicotte.com/post/removing-borders-around-ggplot2-graphs/

这篇关于如何以适当的宽高比保存ggplot2图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆