[英]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])
? 我看了各種方法,但都沒有奏效。
我認為我制作循環的方式似乎是問題所在。 我假設我需要遍歷列表而不是直接遍歷數據框,但是我不確定如何執行此操作。
嘗試這個。 您必須遍歷變量的名稱。 我添加了以 ## 開頭的注釋,其中我更改了您的代碼。
#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.