Search code examples
rggplot2

Assigning a dynamic name to a plot in R?


createMap <- function(df1) {

map <- get_googlemap(center="Milwaukee") %>% ggmap()+
    stat_density2d(data=df1, aes(x=Longitude, y=Latitude, fill=..density..),geom='tile', contour=F, alpha=.5)+
labs(fill="seizure density")+
scale_fill_viridis(option="inferno")

return map
}

createMap(my_df)

I want to call this function to return a plot that is named: map_my_df (i.e. the name of the dataset is included in the name). In other words, I want to name the plot dynamically (not the plot tile, I mean the actual variable name of the plot) with this function and have that plot globally available outside of the function.

Using the following doesn't work:

paste(map,df1,sep="_") <- get_googlemap(center="Milwaukee") %>% ggmap()+
        stat_density2d(data=df1, aes(x=Longitude, y=Latitude, fill=..density..),geom='tile', contour=F, alpha=.5)+
    labs(fill="seizure density")+
    scale_fill_viridis(option="inferno")

Solution

  • I think you are after assign.

    createMap <- function(df1) {
      
      map <- ggplot(mtcars, aes(wt, mpg)) +
      geom_point()
      
      name <- paste("map", deparse(substitute(df1)), sep="_")
      assign(name, map, envir = .GlobalEnv)
    }
    
    createMap(mtcars)
    
    map_mtcars
    

    enter image description here