【问题标题】:Consecutive plots numbering连续地块编号
【发布时间】:2021-03-02 07:55:44
【问题描述】:

在 R Markdown 中,我生成了一个包含多个图的报告。我需要在每个图的标题中添加“图##”,以便这些数字是连续的。 目前我的方法是使用变量fig,并在每次绘图后加1。

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;

我的问题是我经常忘记在情节后添加fig = fig + 1;。有什么优雅的方法可以避免这种重复输入吗?

更新:reprex 已更新以更清楚地显示问题。

【问题讨论】:

    标签: r ggplot2 r-markdown


    【解决方案1】:

    试着这样做

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

    reprex package (v1.0.0) 于 2021-03-02 创建

    【讨论】:

    • 对不起,我的代表不是很清楚我想要什么。我已经更新了 reprex 以更好地显示问题 - 我无法以编程方式生成图,因为它们彼此完全不同。
    猜你喜欢
    • 2020-03-19
    • 1970-01-01
    • 2021-03-28
    • 2018-02-21
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    相关资源
    最近更新 更多