Skip to content

Instantly share code, notes, and snippets.

@JosiahParry
Created October 16, 2025 15:32
Show Gist options
  • Save JosiahParry/a013c715dc719abf075a0cd1193f5aed to your computer and use it in GitHub Desktop.
Save JosiahParry/a013c715dc719abf075a0cd1193f5aed to your computer and use it in GitHub Desktop.
library(ggplot2)
all_plots <- list()
m <- as.matrix(penguins[,3:6])
for (i in 1:ncol(m)) {
gg <- ggplot(penguins, aes(bill_len, m[,i])) +
geom_point() +
labs(title = sprintf("Column %i", i))
all_plots[[i]] <- gg
}
gg_for <- patchwork::wrap_plots(all_plots)
manual_plots <- list()
manual_plots[[1]] <- ggplot(penguins, aes(bill_len, m[,1])) +
geom_point() +
labs(title = "Column 1")
manual_plots[[2]] <- ggplot(penguins, aes(bill_len, m[,2])) +
geom_point() +
labs(title = "Column 2")
manual_plots[[3]] <- ggplot(penguins, aes(bill_len, m[,3])) +
geom_point() +
labs(title = "Column 3")
manual_plots[[4]] <- ggplot(penguins, aes(bill_len, m[,4])) +
geom_point() +
labs(title = "Column 4")
gg_manual <- patchwork::wrap_plots(manual_plots)
gg_for | gg_manual
@TimTaylor
Copy link

bang bang

for (i in 1:ncol(m)) {
    gg <- ggplot(penguins, aes(bill_len, m[,!!i])) + geom_point() + labs(title = sprintf("Column %i", i))
    all_plots[[i]] <- gg
}

@JosiahParry
Copy link
Author

bang bang? nse banned 5ever now.

@TimTaylor
Copy link

bang bang operator !!. That's what I've always called it but not sure why

@jrosell
Copy link

jrosell commented Oct 16, 2025

What if...

library(ggplot2)

all_plots <- list()

m <- as.matrix(penguins[,3:6])
m_cols <- colnames(penguins[,3:6])

for (i in 1:ncol(m)) {  
  gg <- ggplot(m, aes(bill_len, .data[[m_cols[i]]])) + 
    geom_point() +
    labs(title = sprintf("Column %i", i))
  all_plots[[i]] <- gg
}

gg_for <- patchwork::wrap_plots(all_plots)
gg_for

I guess it would be wonderful to be able have .data[[i]] instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment