R//ggplot2:组合facet_wrap和for循环时的动态标题

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

我有一个时空数据集,其中包含我希望加班绘制的一组位置的各种指标。

这是我的 facet_wrap + 循环

#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)
}

问题是 ggtitle 中没有 var i 的实际名称,我得到了第一个值。如何为每个图正确地遍历 names(df_poly[40:42])?我研究了多种方法,但其中 none 行得通。

我认为我制作循环的方式似乎是问题所在。我假设我需要遍历一个列表而不是直接遍历数据框,但是我不确定该怎么做。

试试这个。您必须遍历变量的名称。我在更改您的代码的地方添加了以## 开头的注释。

#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)
}