简体   繁体   English

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

[英]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这是我的 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)
}

The problem is that instead of having the actual names of var i in ggtitle I get the first value.问题是,我得到了第一个值,而不是在ggtitle中使用 var i的实际名称。 How do I get to iterate through the names(df_poly[40:42]) properly for each of the plots?如何为每个图正确迭代names(df_poly[40:42]) 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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