【问题标题】:Using long figures in markdown在降价中使用长数字
【发布时间】:2018-06-27 15:16:04
【问题描述】:

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

这些很长,因为它们使用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)
```

【问题讨论】:

  • 好问题!我曾经在类似的事情上苦苦挣扎,然后我偶然发现:Dynamic height and width for knitr plots。 “假设您想使用循环输出一堆图,但您希望它们每个都有不同的大小”,“或者让数据定义大小”。也许,也许对你有用?也许还有:Print a list of dynamically-sized plots in knitr
  • 这非常有用,非常感谢,实际上几乎是重复的。我不知道我可以只使用变量而不是固定参数。但是为了增加一点趣味,让我的报告看起来真的很好,我会添加一个请求。如果我只是将我的高度设置为n * single_height,由于边距和标签尺寸是固定的,这些数字仍会或多或少地被拉伸,我该如何解释呢?
  • 我只是拖延了我必须完成的评论,我需要回到那个...抱歉,现在无法为您提供更多帮助。祝你好运!
  • 祝你审查顺利:)

标签: r ggplot2 markdown knitr


【解决方案1】:

遵循n * single_height 的想法:您可以使用块选项eval.after,以便在评估块的其余部分之后评估fig.widthfig.height 选项,然后使用@987654327 @ 拆分 ggplot 对象并确定构面中使用的行数和列数。

例如:

---
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
```

生成的 html 截图如下:

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

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 2018-10-02
    相关资源
    最近更新 更多