Reputation: 301
I am trying to create 6 ggplot objects graphing the same graph but labeled differently, the labeling being stored in object{1:6}
ggrun<- c(1,2,3,4,5,6)
for(i in ggrun) {assign(paste0("ggplot_", i),
(ggplot(DF1, aes(x=X, y=Y, color=as.factor(get(paste0("object", i))[["cluster"]]))) + geom_point(fill = NA, size=1, alpha=0.6)))}
But this produced 6 identical objects, with the proper {1:6} names, but all with the same value of object6
.
I checked my for loop too,
for(i in ggrun) {print(table(get(paste0("hdbscan_object", ggrun[i]))[["cluster"]]))}
and it spat out 6 distinct tables.
further, to make sure it was not my plotting command:
grid.arrange(grobs = g, ncol(3), nrow(2), top="Title of Graphs")
I manually assigned each item in the list object, e.g.:
g[[5]] = ggplot(DF1, aes(x=PC1, y=PC4, color=as.factor(get(paste0("object", "5"))[["cluster"]])))
+ geom_point(fill = NA, size=1, alpha=0.6)
and it ran correctly.
Upvotes: 0
Views: 62
Reputation: 388807
Here's another way using mget
:
library(ggplot2)
lapply(mget(paste0("object", 1:6)), function(x) {
ggplot(DF1, aes(x=PC1, y=PC4,
color= factor(x[["cluster"]]))) +
geom_point(fill = NA, size=1, alpha=0.6)
}) -> list_plots
list_plots
Upvotes: 1
Reputation: 1388
ggplot works a bit weirdly with for loops as many of the internal operations seem to rely on pointers rather than actually storing the values. To work around this, you will often have to create a new environment for them to protect from the value that the pointer points at from being changed.
You can try storing the values in a list and using the lapply
function:
g <- lapply(1:6,
function (x){
ggplot(DF1, aes(x=PC1, y=PC4,
color=as.factor(get(paste0("object", x))[["cluster"]]))) +
geom_point(fill = NA, size=1, alpha=0.6)
}
)
Upvotes: 1