【问题标题】:Creating graphs in a loop: one graph different from the others在循环中创建图形:一个图形与其他图形不同
【发布时间】:2020-10-14 21:22:55
【问题描述】:

我有一个精心制作的代码来创建一系列图表。我想在我创建的众多图表之一中添加一条垂直线。

考虑以下简单代码:

library(ggplot2)
library(grid)
library(gridExtra)


plots <- list()

for (i in 1:4) {
  V1 <- rnorm(1000)
  V2 <- seq(1000)
  df <- data.frame(V1, V2)

plots[[i]] <- ggplot(df, aes(x= V2, y=V1)) +
    geom_point()+
    geom_vline(xintercept = 500, color="red")
}


grid.arrange(grobs=plots, nrow=2)

我想要图 4 的红色垂直线,而不是其他的。我将如何有效地做到这一点?

【问题讨论】:

    标签: r for-loop ggplot2 gridextra geom-vline


    【解决方案1】:

    只需拆分您的情节生产并设置条件:)

    library(ggplot2)
    library(grid)
    library(gridExtra)
    
    
    plots <- list()
    
    for (i in 1:4) {
        V1 <- rnorm(1000)
        V2 <- seq(1000)
        df <- data.frame(V1, V2)
        
        plots[[i]] <- ggplot(df, aes(x= V2, y=V1)) +
            geom_point()
        if (i == 4) plots[[i]] <- plots[[i]] + geom_vline(xintercept = 500, color="red")
    }
    
    
    grid.arrange(grobs=plots, nrow=2)
    

    【讨论】:

    【解决方案2】:

    对于这个问题,您不需要 for 循环和 if 语句。您可以使用刻面;

    library(ggplot2)
    library(grid)
    library(gridExtra)
    library(dplyr)
    
    set.seed(123) ## set the seed for random numbers to be reproducible
    df <- bind_rows(lapply(1:4, function(x) 
                                  data.frame(V1=rnorm(1000), V2=seq(1000))), .id = 'facet')
    
    ggplot(df, aes(x= V2, y=V1)) +
      geom_point() +
      facet_wrap(~facet) +
      geom_vline(data=data.frame(xint=500,facet=4), aes(xintercept = xint), color = "red")
    

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 1970-01-01
      • 2011-10-22
      • 2014-12-04
      • 2018-09-18
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多