首页 > 解决方案 > 使用 expand_limits 的 ggplot 结合使用 get 函数的 facet_wrap 崩溃

问题描述

考虑一个需要使用 facet_wrap 生成 ggplot 的简单 data.frame

library(ggplot2)
dt <- data.frame(id=c(rep("a",10),rep("b",10)),time=c(1:10,1:10),value=c(1:10,20:11))
facet_var <- "id"

有谁知道为什么前两行运行完美,而第三行却不运行?似乎 ggplot2 不喜欢 expand_limits 和 facet_wrap 一起进入。

ggplot(dt,aes(time,value))+geom_line()+facet_wrap(~base::get(facet_var))                 
ggplot(dt,aes(time,value))+geom_line()+facet_wrap(~id)+expand_limits(y=0)
ggplot(dt,aes(time,value))+geom_line()+facet_wrap(~base::get(facet_var))+expand_limits(y=0)

Error in base::get(facet_var) : object 'id' not found

这发生在 ggplot2 版本 3.0.0 和 3.1.0

> sessionInfo()
R version 3.4.3 (2017-11-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggplot2_3.1.0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.15     withr_2.1.2      dplyr_0.7.4      assertthat_0.2.0 grid_3.4.3       plyr_1.8.4      
 [7] R6_2.2.2         gtable_0.2.0     magrittr_1.5     scales_0.5.0     pillar_1.1.0     rlang_0.2.1     
[13] lazyeval_0.2.1   bindrcpp_0.2     labeling_0.3     tools_3.4.3      glue_1.2.0       munsell_0.4.3   
[19] yaml_2.1.16      compiler_3.4.3   pkgconfig_2.0.1  colorspace_1.3-2 bindr_0.1        tibble_1.4.2  

标签: rggplot2facet-wrap

解决方案


推荐阅读