尽管我在这里使用水平条形图作为示例,但这本身并不是问题。一般的问题是如何处理使用后在 rmarkdown 中围绕 ggplots 创建的空白区域



为了减少条形图使用的空间,尤其是很少的因素,我更喜欢水平条形图,我使用 coord_fixed(ratio=...) 在条形图的宽度和长度之间设置合理的比例。

情节本身看起来像我想要的那样(见下面的第一个例子),但它周围有很多空白,我试图通过在 knitr-header 中使用 fig.height = ... 来删除它们。正如下一个示例所示,结果并不理想。

library(ggplot2)
library(ggstance)
library(dplyr)

X <- data.frame(X = sample(c("A", "B"), 30, replace = TRUE))
X <- X %>% group_by(X) %>% summarise(n = n())
ggplot(X, aes(y = X, x = n))+
   geom_barh(stat = "identity")+
   coord_fixed(ratio = 1)+
   ggtitle("blub")

在我使用 x = 3 的 rmarkdown 中使用它; x = 1 ; x=0.5:
```{r,fig.height = x}

# see code above
```

这导致:

图高度=3

ggplots周围的Rmarkdown裁剪空白-LMLPHP

图高度=1

ggplots周围的Rmarkdown裁剪空白-LMLPHP

图高度=0.5

ggplots周围的Rmarkdown裁剪空白-LMLPHP

我希望它能做什么:
  • 裁剪白边
  • 同时保持绘图(绘图 +(轴)标题)区域本身不变

  • 后者显然不会发生,因为情节区域变窄并且标题移动到情节内部。

    不知道是在ggplot里面还是在knitr里面找到解决办法。最重要的是,一个理想的解决方案应该很容易自动化以在循环内使用(使解决方案适应不断变化的因素数量)。

    最佳答案

    您可以将参数传递给 fig.widthfig.height 块选项。您只需要在评估该块之前计算它们:

    ---
    output: html_document
    ---
    
    ```{r, message=FALSE}
    library(ggplot2)
    library(ggstance)
    library(dplyr)
    
    X <- data.frame(X = sample(c("A", "B"), 30, replace = TRUE))
    X <- X %>% group_by(X) %>% summarise(n = n())
    
    hei <- length(X$X) + 1
    len <- max(X$n) + 2
    
    ```
    
    Text before the plot
    ```{r, fig.height=hei, fig.width=len, echo=FALSE}
    
    ggplot(X, aes(y = X, x = n))+
      geom_barh(stat = "identity")+
      coord_fixed(ratio = 1)+
      ggtitle("blub") +
      theme(plot.background = element_rect(fill = 'red'))
    
    ```
    
    Text after the plot
    
    ```{r, message=FALSE}
    
    X <- data.frame(X = sample(c("A", "B", "C"), 30, replace = TRUE))
    X <- X %>% group_by(X) %>% summarise(n = n())
    
    hei <- length(X$X) + 1
    len <- max(X$n) + 2
    
    ```
    Another plot
    ```{r, fig.height=hei, fig.width=len, echo=FALSE}
    
    ggplot(X, aes(y = X, x = n))+
      geom_barh(stat = "identity")+
      coord_fixed(ratio = 1)+
      ggtitle("blub") +
      theme(plot.background = element_rect(fill = 'red'))
    
    ```
    

    结果:
    ggplots周围的Rmarkdown裁剪空白-LMLPHP

    关于ggplots周围的Rmarkdown裁剪空白,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44279652/

    10-12 17:41
    查看更多