循环创建图形:一个图形与另一个图形不同

时间:2020-06-24 15:02:20

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

我有一个详尽的代码来创建一系列图形。我想在创建的许多图形之一中放置一条垂直线。

考虑以下简单代码:

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中有红色的垂直线,但没有其他。我将如何有效地做到这一点?

2 个答案:

答案 0 :(得分: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")

答案 1 :(得分:0)

只划分地块的生产并设置条件:)

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)