Oleg
Oleg

Reputation: 141

Consecutive plots numbering

In R Markdown I generate a report that contain multiple plots. I need to add "Fig. ##" to the title of each plot, so that these numbers are consecutive. At the moment my approach is to use variable fig and add 1 to it after each plot.

library(ggplot2);

fig = 1;

ggplot(mtcars)+
  geom_point(aes(x = cyl,
                 y = disp))+
  labs(title = paste0("Fig. ", fig, ". Cyl vs Disp"));
fig = fig + 1;

## Some extra code or chunk break

ggplot(iris)+
  geom_point(aes(x = Sepal.Length,
                 y = Petal.Length))+
  labs(title = paste0("Fig. ", fig, ". Sepal vs Petal"));
fig = fig + 1;

My problem is that I often forget to add fig = fig + 1; after the plot. Is there any elegant way how to avoid this repetitive typing?

UPDATE: reprex was updated to more clearly show the problem.

Upvotes: 1

Views: 183

Answers (1)

Yuriy Saraykin
Yuriy Saraykin

Reputation: 8880

try to do it this way

library(tidyverse)
fn_plot <- function(data, x, y, fig){
  ggplot(data)+
    geom_point(aes(x = .data[[x]],
                   y = .data[[y]])) +
    labs(title = paste0("Fig. ", fig, " . ", x, " vs ", y))
}

data <- list(mtcars, iris)
x <- c("cyl", "Sepal.Length")
y <- c("disp", "Petal.Length")
fig <- 1:2

l <- list(data, x, y, fig)

pmap(.l = l, .f = fn_plot)
#> [[1]]

#> 
#> [[2]]

Created on 2021-03-02 by the reprex package (v1.0.0)

Upvotes: 1

Related Questions