R//ggplot2:结合facet_wrap和for循环时的动态标题 [英] R//ggplot2: Dynamic title when combining facet_wrap and for loop

查看:34
本文介绍了R//ggplot2:结合facet_wrap和for循环时的动态标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时空数据集,其中包含各种指标,用于指示我希望加班的一组位置.

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

这是我的facet_wrap +循环

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

问题在于,我没有在 ggtitle 中使用var i 的实际名称,而是获得了第一个值.如何正确遍历每个图的 names(df_poly [40:42])?我研究了各种方法,但没有一个起作用.

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.

推荐答案

尝试一下.您必须遍历您的var的名称.我添加了以##开头的注释,并在其中更改了您的代码.

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

这篇关于R//ggplot2:结合facet_wrap和for循环时的动态标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆