Rmarkdown автоматически использует функцию на графиках - PullRequest
0 голосов
/ 06 февраля 2019

Я создаю документ RMarkdown, в котором каждый блок создает график.

Для каждого из этих графиков я хотел бы применить специальную функцию форматирования, которая регулирует способ отображения заголовка.

Есть ли способ указать knitr / rmarkdown применить эту специальную функцию к графику каждого блока?Например, может быть, есть опция чанка, например {r, fig.function = adjust_title_position}?

. Мотивация заключается в том, что я не хочу повторять вызов функции отдельно для каждого графика (например, adjust_title_position(plot_42)) и в то же времявремя, я не хочу использовать что-то вроде lapply(my_plots, adjust_title_position), что потребовало бы определения всех графиков в одном месте.

Ниже приведен минимальный пример файла RMarkdown, к которому это можно применить.

---
title: "RMD_Example"
output: html_document
---

```{r setup, include=FALSE}
# Load ggplot2
library(ggplot2)

# Define helper function
  adjust_title_position <- function(p) {
    # Shift the horizontal position of the plot title
    p_built <- invisible(ggplot2::ggplot_build(p))
    gt <- invisible(ggplot2::ggplot_gtable(p_built))
    gt$layout[which(gt$layout$name == "title"), c("l", "r")] <- c(2, max(gt$layout$r))

    # Prints the plot to the current graphical device
      gridExtra::grid.arrange(gt, newpage = TRUE)
    # Invisibly return the gtable object  
      invisible(gt)
  }

```


```{r plot_1}
ggplot(mtcars) + geom_point(aes(x = wt, y = mpg)) +
  labs(title = "Weights and miles-per-gallon")
```

```{r plot_2}
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() +
  labs(title = "Sepal length and width")
```

1 Ответ

0 голосов
/ 08 февраля 2019

Вы можете перерегистрировать print -метод для ggplot -объектов.

# Define helper function
adjusted_title_position <- function(p) {
  # Shift the horizontal position of the plot title
  p_built <- invisible(ggplot2::ggplot_build(p))
  gt <- invisible(ggplot2::ggplot_gtable(p_built))
  gt$layout[which(gt$layout$name == "title"), c("l", "r")] <- c(2, max(gt$layout$r))

  # Prints the plot to the current graphical device
  gridExtra::grid.arrange(gt, newpage = TRUE)
}

# Reregister print.ggplot
assignInNamespace("print.ggplot", adjusted_title_position, asNamespace("ggplot2"))
...