Please look at the following example code, if wants to generate multiple similar plots by a function, how to make the plot file (p) available outside the function?
library(ggplot2)
library(gganimate)
library(gapminder)
newplot<- function(){
p <- ggplot(
gapminder, aes(x = gdpPercap, y=lifeExp, size = pop, colour = country)) +
geom_point(show.legend = FALSE, alpha = 0.7) +
scale_color_viridis_d() +
scale_size(range = c(2, 12)) +
scale_x_log10() +
labs(x = "GDP per capita", y = "Life expectancy")
return(p)
}
newplot()
p + transition_time(year)
The example code is simple, but the real task is much more complicated, many parameters required to change. The issue is "p + transition_time(year)" doesn't work, I guess the p that is created by function does not exist outside the function. Can anyone help solve the problem? Thanks.