I have created a number of graphs looping a ggplot script, and now I want to add the same axis title and text to a selection of the graphs (without getting too much into it, it made sense to initially make the graphs with empty y axes, since the majority of them will remain empty).
The code for adding the title to a single graph works without issue, but I get an error when I try to do it via a loop. Sorry I don't supply the data in the question to reproduce, it would take me days to even figure out how to do that and the data isn't publicly available
The graphs are stored in a list 'p' and called
p$A, p$B, p$C, etc
Rather than doing it individually for each graph I want to simultaneously edit the Y axis of a number of these. I first created the object containing just the graphs I want to change
change.plots <- c(p$B, p$G, p$J, p$S)
I tried the following code and it worked on an individual graph
p$G
labs(y = "Loudness")
theme(axis.text.y = element_text())
But when I try do it through this loop
temp <- list()
for(i in 1:4) {
temp[[i]] <- change.plots[i]
labs(y = "Loudness")
theme(axis.text.y = element_text())
}
I get the following error
Error in change.plots[i] labs(y = "Loudness") : non-numeric argument to binary operator
Can anyone tell me where the loop is going wrong? Thanks
CodePudding user response:
The issue is that you use single square brackets [
which will return a list with one element. Hence you get an error. Instead you have to use double square brackets [[
to extract the elements of your plot list which will return a ggplot object. For more on the difference between [
and [[
see this post.
Note: Instead of storing the plots to change in a separate list a simpler approach would be to loop over a list of the names of the plots you want to change as I do in my code below.
Using some fake random example data:
library(ggplot2)
# Example plots
p <- lapply(1:4, function(x) ggplot(data.frame(x = seq(x), y = seq(x)), aes(x, y)) geom_point())
names(p) <- LETTERS[1:4]
# Names of plots to change
change.plots <- c("A", "C")
temp <- list()
for(i in change.plots) {
temp[[i]] <- p[[i]]
labs(y = "Loudness")
theme(axis.text.y = element_text())
}
temp
#> $A
#>
#> $C
Instead of a for loop you could achieve the same result using lapply
:
lapply(p[idx], function(x) x labs(y = "Loudness") theme(axis.text.y = element_text()))