我正在阅读 Hadley Wickham 的“R for Data Science”,他在 ggplot 调用中使用 ~var
。
我理解y ~ a + bx
,其中~
描述了因变量和自变量之间的公式/关系,但是~var
是什么意思意思是?更重要的是,为什么不能直接放置变量本身呢?请参阅下面的代码:
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(~ class, nrow = 2)
或
demo <- tribble(
~cut, ~freq,
"Fair", 1610,
"Good", 4906,
"Very Good", 12082,
"Premium", 13791,
"Ideal", 21551
)
ggplot(data = demo) +
geom_bar(mapping = aes(x = cut, y = freq), stat = "identity")
最佳答案
这只是ggplot
利用formula
结构让用户决定要考虑哪些变量。来自?facet_grid
:
For compatibility with the classic interface, rows can also be a formula with the rows (of the tabular display) on the LHS and the columns (of the tabular display) on the RHS; the dot in the formula is used to indicate there should be no faceting on this dimension (either row or column).
所以 facet_grid(. ~ var)
只是意味着在变量 var
上对网格进行分面,分面分布在列上。它与facet_grid(col = vars(var))
相同。
尽管看起来像一个公式
,但它实际上并没有被用作公式:它只是一种向 R 呈现多个参数的方法,facet_grid
代码可以清晰明确地解释。
关于r - 单个变量前面的波形符 (~) 是什么意思 (facet_wrap)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51901398/