在 Markdown 中使用长数字

Moo*_*per 5 markdown r ggplot2 knitr

我在降价报告中显示长数字。

它们很长,因为它们使用的ggplot2::facet_wrap高度取决于数据,而数据不是恒定的。

我可以设置figure.height块的参数,但随后它被修复,并且我的报告看起来很糟糕。他们有办法解决这个问题吗?

例子 :

---
title: "title"
author: "author"
date: '`r Sys.Date()`'
output: html_document
---

```{r, figure.height=40}
library(dplyr)
library(ggplot2)
iris %>%
  mutate_at("Sepal.Length",cut, 5) %>%
  mutate_at("Sepal.Width",cut,2) %>%
  group_by_at(c(1,2,5)) %>%
  summarize_at("Petal.Length",mean) %>%
  ggplot(aes(Species, Petal.Length)) +
  geom_col() +
  facet_wrap(Sepal.Length ~ Sepal.Width,ncol=2)
```
Run Code Online (Sandbox Code Playgroud)

Pet*_*ter 1

为了遵循这个n * single_height想法:您可以使用 chunk 选项,eval.after以便在评估块的其余部分后评估fig.width和选项,然后使用来分离 ggplot 对象并确定在该块中使用的行数和列数方面。 fig.heightggplot_build

例如:

---
author: "author"
date: '`r Sys.Date()`'
output: html_document
---

```{r setup}
library(dplyr)
library(ggplot2) 
library(knitr)

FACET_HEIGHT = 3.4
FACET_WIDTH  = 5

opts_chunk$set(out.width = "80%",
               out.height = "80%",
               eval.after = c("fig.height", "fig.width"))
```

For the example we'll have one basic plot to which we will set different facets.
```{r}
g <- 
  iris %>%
  mutate_at("Sepal.Length",cut, 5) %>%
  mutate_at("Sepal.Width",cut,2) %>%
  group_by_at(c(1,2,5)) %>%
  summarize_at("Petal.Length",mean) %>%
  ggplot(aes(Species, Petal.Length)) +
  geom_col()
```

A graphic with two columns
```{r fig1, fig.height = FACET_HEIGHT * max(ggplot_build(g1)$layout$layout$ROW), fig.width = FACET_WIDTH * max(ggplot_build(g1)$layout$layout$COL)}
g1 <- g + facet_wrap(Sepal.Length ~ Sepal.Width, ncol = 2)
g1
```


A graphic with two rows
```{r fig2, fig.height = FACET_HEIGHT * max(ggplot_build(g2)$layout$layout$ROW), fig.width = FACET_WIDTH * max(ggplot_build(g2)$layout$layout$COL)}
g2 <- g + facet_wrap(Sepal.Length ~ Sepal.Width, nrow = 2)
g2
```
Run Code Online (Sandbox Code Playgroud)

生成的 html 的屏幕截图是:

在此输入图像描述

需要对图像宽度和高度进行一些微调,但这应该是一个很好的起点。