【发布时间】:2021-06-15 08:52:27
【问题描述】:
Here 是解决该问题的一些解决方法,但是您是否有理由可以在ggplot2::facet_grid() 中为rows 传递一个字符串,但不能为cols 传递一个字符串?
这有效(注意rows 属性):
f_varname <- 'drv'
ggplot( mpg, aes( displ, cty ) ) + geom_point() +
facet_grid( rows = f_varname )
但这不是(注意cols 属性):
f_varname <- 'drv'
ggplot( mpg, aes( displ, cty ) ) + geom_point() +
facet_grid( cols = f_varname )
# => Error: `cols` must be `NULL` or a `vars()` specification
相反,您必须对cols 使用vars() 规范:
ggplot( mpg, aes( displ, cty ) ) + geom_point() +
facet_grid( cols = vars( drv ) )
哪个不能处理字符串:
f_varname <- 'drv'
ggplot( mpg, aes( displ, cty ) ) + geom_point() +
facet_grid( cols = vars( f_varname ) )
# =>
# Error: At least one layer must contain all faceting variables: `f_varname`.
# * Plot is missing `f_varname`
# * Layer 1 is missing `f_varname`
从链接的讨论中,answer 也适用于字符串:
f_varname <- 'drv'
ggplot( mpg, aes( displ, cty ) ) + geom_point() +
facet_grid( reformulate( f_varname ) )
【问题讨论】:
-
从在线文档看来,这是一个遗留功能:“为了与经典界面兼容,行也可以是公式......”。我猜测包含列名称的字符变量可以强制转换为适当的公式。
-
谢谢@Limey。听起来像是一个可能的解释。不过,这些特性总是让我一直使用 R。
标签: r string ggplot2 facet facet-grid