Reputation: 4309
I am using purrr
to make multiple ggplot2
plots. How can I give each x-axis a unique name using a numeric string?
My best attempt (below) is only able to get the first value of the string, so the x-axis of all 3 graphs says 1% explained variance
, when I would like three different names of 1% explained variance
, 2% explained variance
, and 3% explained variance
. Thank you
library(tidyverse)
new<-c(1,2,3)
iris%>%
split(.$Species) %>%
purrr::map2(.y = names(.),
~ ggplot(data=., aes(x=Sepal.Length, y=Sepal.Width))+
geom_point()+
labs(x=paste(round(new,2),'% explained variance', sep=''))
)
Upvotes: 3
Views: 948
Reputation: 887108
In the map2
we can specify the .y
as seq_along(.)
and then use that to index the 'new' because 'new' is a vector of length 3.
l1 <- iris %>%
split(.$Species) %>%
map2( seq_along(.), ~
ggplot(data=., aes(x=Sepal.Length, y=Sepal.Width))+
geom_point()+
labs(x=paste(round(new[.y],2),'% explained variance', sep='')))
NOTE: If we are not using names
, then simply pass the 'new' as .y
(here the names of the list
elements are not used)
The plots could be saved as a single pdf
library(gridExtra)
l2 <- map(l1, ggplotGrob)
ggsave(marrangeGrob(grobs = l2, nrow = 1, ncol =1), file = "plots.pdf")
Or save it as a single png with multiple plots on the same page
ggsave(marrangeGrob(grobs = l2, nrow = 3, ncol =1), file = "plots.png")
Upvotes: 5