简体   繁体   中英

R//ggplot2: Dynamic title when combining facet_wrap and for loop

I have a spatialtemporal dataset with various indicators for a set of location that I wish to map overtime.

Here is my facet_wrap + loop

#basemap
basemap <- ggplot() +
    geom_sf(data= country_adm2) +
  coord_sf() +
  theme_void() 
print(basemap)

#joining dataframe to polygons
df_poly <- left_join(country_adm2, df, by= "County") ##joins the data by County.

#loop & facet_wrap plots
## This goes over the dataset (df_poly) to plot the the three variables, and facet_wrap over ~Date to see time variation (over 12 months)

for(i in df_poly[40:42]){ ## the vars I wish to plot  to iterate the temporal map through
imap <- basemap + 
  geom_sf(aes(fill = i), data= df_poly ) +
  scale_fill_viridis(option = "cividis", direction= 1, alpha= 1, )+
  facet_wrap(~ Date) + ##the temporal facet_wrap
  ggtitle(paste0("Indicators:", i)) +
  labs(fill = "% of\ncovered population")
  print(imap)
}

The problem is that instead of having the actual names of var i in ggtitle I get the first value. How do I get to iterate through the names(df_poly[40:42]) properly for each of the plots? I looked at various ways but none of them worked.

I reckon that the way I make the loop seems to be the issue. I assume I need to loop over a list rather than directly the dataframe, however I am unsure how to do this.

Try this. You have to loop over the names of your vars. I added comments starting with ## where I changed your code.

#basemap
basemap <- ggplot() +
  geom_sf(data= country_adm2) +
  coord_sf() +
  theme_void() 
print(basemap)

#joining dataframe to polygons
df_poly <- left_join(country_adm2, df, by= "County") ##joins the data by County.

#loop & facet_wrap plots
## This goes over the dataset (df_poly) to plot the the three variables, and facet_wrap over ~Date to see time variation (over 12 months)

## loop over the names of the vars to plot
for(i in names(df_poly)[40:42]){ ## the vars I wish to plot  to iterate the temporal map through
  imap <- basemap + 
    ## Convert names to symbols using!!sym()
    geom_sf(aes(fill = !!sym(i)), data = df_poly ) +
    scale_fill_viridis(option = "cividis", direction= 1, alpha= 1, )+
    facet_wrap(~ Date) + ##the temporal facet_wrap
    ggtitle(paste0("Indicators:", i)) +
    labs(fill = "% of\ncovered population")
  print(imap)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM