我想用R标记创建一个html输出,其中包括用ggmap()生成的绘图的集合.当 map (或分面 map )的宽度大于高度时,html输出中的绘图上方和下方都有空白,我希望自动删除这些空白,而不需要做太多额外的工作.

空格之前已经在这里讨论过.我发现的一种解决方案是适当地指定Fig.Height和Fig.Width(手动try ).然而,我宁愿避免 for each 地块try 合适的高/宽值,因为我的每个地块都有不同的高/宽比.

以前的 idea 是计算出绘图的宽/高比,然后指定图.asp: How to remove white space above and below image in R Markdown?个 有人提出了一个借助R函数来确定比率的函数: Rmarkdown crop white space around ggplots 但这仅在将绘图另存为PNG作为中间步骤时才起作用.

有没有办法调整绘图的边距或如何将其包含在markdown automatically中(无需绕过保存的图像或手动调整某些高度/宽度/asp值)以删除绘图上方和下方的额外空白?

以下是一个实用示例:

---
title: "Plot margins"
output: html_document
---

The following plot has some white space above and below it.

```{r, echo=FALSE, message=FALSE, cache=TRUE}
require(ggmap)
df <- data.frame(lon = c(14.04, 14.06), lat = c(53.04, 53.07), species = c("species_1", "species_2"))
cbbox <- make_bbox(lon = c(14.0, 14.2), lat = c(53.0, 53.1), f = .1)
map_data <- get_map(location = cbbox,  source = "stamen")
ggmap(map_data) +
  geom_point(data = df,
             aes(x=lon, y=lat), size=2) +
  facet_wrap(~ species, ncol=2)
```

The next plot does not have that large white margin.

```{r, echo=FALSE, message=FALSE, cache=TRUE}
require(ggmap)
df <- data.frame(lon = c(14.04, 14.06), lat = c(53.04, 53.07), species = c("species_1", "species_2"))
cbbox <- make_bbox(lon = c(14.0, 14.2), lat = c(53.0, 53.1), f = .1)
map_data <- get_map(location = cbbox,  source = "stamen")
ggmap(map_data) +
  geom_point(data = df,
             aes(x=lon, y=lat), size=2)
```

Some text below.

推荐答案

更新:

原创内容在底部

考虑到最初的答案,我查看了函数get_dims()以查看数据是如何收集的.

我发现,让它忽略预设的体形大小是非常容易的.我建议您将此函数作为块添加到其自身中.你也不需要打DeLuciatoR图书馆的电话.

我保留了该函数的原始代码get_dims(),将其重命名为getDims(),并注释掉了导致RMarkdown预设图形大小问题的部分.您可以直接删除该部分,但我认为从包中查看原始代码可能会很有用.

```{r getterDims}
getDims = function(ggobj, maxheight, maxwidth = maxheight, units = "in", 
    ...) 
{
    # if (inherits(ggobj, "ggplot") && !isTRUE(ggobj$respect) && 
    #     is.null(ggobj$theme$aspect.ratio) && is.null(ggobj$coordinates$ratio) && 
    #     is.null(theme_get()$aspect.ratio)) {
    #     return(list(height = maxheight, width = maxwidth))
    # }
    tmpf = tempfile(pattern = "dispos-a-plot", fileext = ".png")
    png(filename = tmpf, height = maxheight, width = maxwidth, 
        units = units, res = 120, ...)
    on.exit({
        dev.off()
        unlink(tmpf)
    })
    if (inherits(ggobj, "ggplot")) {
        g = ggplotGrob(ggobj)
    }
    else if (inherits(ggobj, "gtable")) {
        g = ggobj
    }
    else {
        stop("Don't know how to get sizes for object of class ", 
            deparse(class(ggobj)))
    }
    stopifnot(grid::convertUnit(grid::unit(1, "null"), "in", 
        "x", valueOnly = TRUE) == 0)
    known_ht = sum(grid::convertHeight(g$heights, units, valueOnly = TRUE))
    known_wd = sum(grid::convertWidth(g$widths, units, valueOnly = TRUE))
    free_ht = maxheight - known_ht
    free_wd = maxwidth - known_wd
    if (packageVersion("grid") >= "4.0.0") {
        null_rowhts <- as.numeric(g$heights[grid::unitType(g$heights) == 
            "null"])
        null_colwds <- as.numeric(g$widths[grid::unitType(g$widths) == 
            "null"])
        panel_asps <- (matrix(null_rowhts, ncol = 1) %*% matrix(1/null_colwds, 
            nrow = 1))
    }
    else {
        all_null_rowhts <- (grid::convertHeight(.null_as_if_inch(g$heights), 
            "in", valueOnly = TRUE) - grid::convertHeight(g$heights, 
            "in", valueOnly = TRUE))
        all_null_colwds <- (grid::convertWidth(.null_as_if_inch(g$widths), 
            "in", valueOnly = TRUE) - grid::convertWidth(g$widths, 
            "in", valueOnly = TRUE))
        null_rowhts <- all_null_rowhts[all_null_rowhts > 0]
        null_colwds <- all_null_colwds[all_null_colwds > 0]
        panel_asps <- (matrix(null_rowhts, ncol = 1) %*% matrix(1/null_colwds, 
            nrow = 1))
    }
    max_rowhts = free_ht/sum(null_rowhts) * null_rowhts
    max_colwds = free_wd/sum(null_colwds) * null_colwds
    rowhts_if_maxwd = max_colwds[1] * panel_asps[, 1]
    colwds_if_maxht = max_rowhts[1]/panel_asps[1, ]
    height = min(maxheight, known_ht + sum(rowhts_if_maxwd))
    width = min(maxwidth, known_wd + sum(colwds_if_maxht))
    return(list(height = height, width = width))
}
```

现在,当您使用此功能时,无论预设的数字大小是多少,也不管您是否指定为coord_fixed().

例如:

```{r whatChuGot, echo=FALSE, message=FALSE, cache=TRUE}

df <- data.frame(lon = c(14.04, 14.06), lat = c(53.04, 53.07), 
                 species = c("species_1", "species_2"))
cbbox <- make_bbox(lon = c(14.0, 14.2), lat = c(53.0, 53.1), f = .1)
map_data <- get_map(location = cbbox,  source = "stamen")
ggp <- ggmap(map_data) +
  geom_point(data = df,
             aes(x = lon, y = lat), size = 2) +
  facet_wrap(~ species, ncol = 2) + 
  theme(plot.margin = unit(rep(.1, 4), "cm"),
        plot.background = element_rect(fill = "green"),
        panel.background = element_rect(fill = "blue"))

ggpd <- getDims(ggp, maxwidth = 7, maxheight = 8)
```

The new dims are `r ggpd`.

```{r showME,results="asis",fig.height=ggpd$height, fig.width=ggpd$width}
# make me shine
ggp
```

enter image description here



原文:

我使用了DeLuciatoR包中的函数get_dims().这不是克伦的包裹;你必须通过Github才能拿到.

devtools::install_github("infotroph/DeLuciatoR")

如果你用这个函数进行绘图,你会得到最好的尺寸.但是,如果您预先设置了图表大小,然后运行它,您将获得您的预设大小(即,fig.height,fig.width).这有什么关系呢?好的,R减价presets,你的图表大小.您必须绕过这个限制.

首先,我将向你们展示这是如何工作的基本前提.接下来,我将向您展示如何将其合并到R Markdown中.

对于第一个图表,我为背景添加了 colored颜色 ,这样您就可以看到我对页边距做了什么.(有什么;没有什么;所有的爵士乐...)

我给所有的图像添加了边框,这样你就可以看到实际情况和图像之间的区别.

library(tidyverse)
library(ggmap)
library(DeLuciatoR)
ggp <- ggmap(map_data) +
  geom_point(data = df,
             aes(x = lon, y = lat), size = 2) +
  facet_wrap(~ species, ncol = 2) + 
  coord_fixed() +                                       # lat/lon equidistant
  theme(plot.margin = unit(rep(.1, 4), "cm"),           # make the plot margin 1 mm
        plot.background = element_rect(fill = "green"),
        panel.background = element_rect(fill = "blue")) # show me my margins

enter image description here


现在已经创建了图形对象,获取尺寸.

get_dims(ggp, maxwidth = 7, maxheight = 8)
# $height
# [1] 2.229751
# 
# $width
# [1] 7
#  

这是相当了不起的国际海事组织.

coord_fixed()是使这一点在R Markdown中发挥作用的一部分.(它会强制使用预设大小的问题.)另一种 Select 是在RMD之外使用这个get_dims()呼叫(讨厌).可能有很多方法可以设置这一点,以便RMD不会超出最佳维度.你得试一试,看看哪种方法对你有效.

好吧,把这个整合进RMD...

您将把图表分成两个单独的块.首先,调用对象的图形(这里是ggp),并调用维度(这里是ggpd).在单独的块中,打印带有块选项中的尺寸的图表.在第二个块中,ggpd$heightfig.height的设置;ggpd$widthfig.width的设置.

My change; no issues!

```{r whatChuGot,echo=FALSE,message=FALSE,cache=TRUE}

df <- data.frame(lon = c(14.04, 14.06), lat = c(53.04, 53.07), 
                 species = c("species_1", "species_2"))
cbbox <- make_bbox(lon = c(14.0, 14.2), lat = c(53.0, 53.1), f = .1)
map_data <- get_map(location = cbbox,  source = "stamen")
ggp <- ggmap(map_data) +
  geom_point(data = df,
             aes(x = lon, y = lat), size = 2) +
  facet_wrap(~ species, ncol = 2) + 
  coord_fixed() +
  theme(plot.margin = unit(rep(.1, 4), "cm"),
        plot.background = element_rect(fill = "green"),
        panel.background = element_rect(fill = "blue"))

ggpd <- get_dims(ggp, maxwidth = 7, maxheight = 8)
# $height
# [1] 2.229751
# 
# $width
# [1] 7
#      
```
The dims are `r ggpd`.

```{r showMe,results="asis",fig.height=ggpd$height, fig.width=ggpd$width}
# make me shine
ggp
```

enter image description here


如果你有任何问题,请告诉我!

这是我整个RMD的一张照片( colored颜色 在上面,但很有针对性).如果你感觉不到html_document的巨大差距,你可以在.main-container的基础上加上max-width: unset;的风格.无论显示器大小如何,默认像素均为940px.

enter image description here

R相关问答推荐

从载体创建 pyramid

查找具有平局的多个列的最大值并返回列名或平局 destruct 者NA值

在值和NA的行顺序中寻找中断模式

如何删除R中除某些特定名称外的所有字符串?

x[[1]]中的错误:脚注越界

获取列中值更改的行号

将非重复序列高效转换为长格式

R s iml包如何处理语法上无效的因子级别?'

如何计算多个日期是否在一个日期范围内

多个模拟序列间的一种预测回归关系

R:从geom_ol()中删除轮廓并导出为pdf

如何在ggplot2中绘制具有特定 colored颜色 的连续色轮

如何根据数据帧中的值从该数据帧中提取值?

正在导出默认的RStudio主题,还是设置括号 colored颜色 ?

按列中显示的配对组估算NA值

SHILINY中DT列的条件着色

如何构建一个for循环来循环处理动物ID?

如何合并不同列表中的数据文件,包括基于名称的部分匹配,而不是一对一等价

隐藏基于 case 总数的值

如何计算多个变量的百分比与总和的百分比?