使用geom_sf批量创建地图的函数调用失败问题求助
解决geom_sf批量绘图函数的美学映射错误
我来帮你搞定这个问题!你遇到的报错其实是ggplot的非标准求值(NSE)特性导致的——当你在函数里写aes(fill = variable)时,ggplot会傻乎乎地去GA_data_shape里找一列叫variable的数据,但你明明是想把传入的参数(比如rel)作为填充变量,这可不就找不到嘛!
为啥单张图没问题,函数就不行?
单张地图的代码里,你直接写aes(fill = rel),ggplot一眼就认出rel是数据框里的列;但在函数里,variable是你定义的参数,ggplot不会自动把它解析成你传入的实际变量名,而是把它当成一个字面意义上的列名去查找,自然就报错了。
最简单的修复方法
用大括号插值{{ }}(大家俗称"拥抱"操作符)来给ggplot提个醒:这里的variable是函数的参数,得替换成我传进去的实际变量!修改后的函数代码如下:
mapping <- function(variable, ltitle, ptitle, stitle){ ggplot(data = GA_data_shape) + geom_sf(aes(fill = {{ variable }}), color = NA) + scale_fill_viridis_c(option = "magma") + theme_void() + labs(fill = ltitle, title = ptitle, subtitle = stitle) + theme(legend.position = "right", legend.title = element_text(size = 8, face = "bold"), legend.text = element_text(size = 8), plot.title = element_text(face = "bold", color = "black"), plot.subtitle = element_text(face = "italic", color = "black")) } # 调用函数,和你原来的写法一样就行 rainfall <- mapping(variable = rel, ltitle = "Rainfall (inches)", ptitle = "Georgia", stitle = "Relative rainfall") rainfall
为啥{{ }}能解决问题?
这个语法是rlang包提供的(ggplot2依赖它),它的作用就是在ggplot的美学映射里"注入"函数的参数值。当你传入rel时,{{ variable }}会自动替换成rel,这样ggplot就能正确识别它是数据框里的列了。
另一种可选方案(用.data代词)
如果你觉得大括号插值有点抽象,也可以用.data代词来明确指定变量来自数据框,不过这种方式需要把变量名以字符串形式传入:
mapping <- function(variable, ltitle, ptitle, stitle){ ggplot(data = GA_data_shape) + geom_sf(aes(fill = .data[[variable]]), color = NA) + scale_fill_viridis_c(option = "magma") + theme_void() + labs(fill = ltitle, title = ptitle, subtitle = stitle) + theme(legend.position = "right", legend.title = element_text(size = 8, face = "bold"), legend.text = element_text(size = 8), plot.title = element_text(face = "bold", color = "black"), plot.subtitle = element_text(face = "italic", color = "black")) } # 调用时变量要传字符串哦 rainfall <- mapping(variable = "rel", ltitle = "Rainfall (inches)", ptitle = "Georgia", stitle = "Relative rainfall") rainfall
内容的提问来源于stack exchange,提问作者kaseyzapatka
相关产品推荐
相关产品推荐

