How to make the plot available outside of the function?

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?


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")


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.

Yes, but that is easy to solve, just assign the output to a variable in your global environment.

p <- newplot()

p + transition_time(year)
1 Like

Thank you so much! It works.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.