r - 单个变量前面的波形符 (~) 是什么意思 (facet_wrap)?

标签 r ggplot2

我正在阅读 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/

相关文章:

r - 如何更改 Shiny 仪表板标题的颜色和字体?

r - 将调色板分配给ggplot2中的元素

r - 是否可以修复 geom_text() 生成的锯齿状、质量差的文本?

r - 基于大小的饼图代码不起作用

r - 如何将日期转换为最近的周末(星期六)

R:具有给定坐标的快速滑动窗口

使用ggplot在ecdf图中反转x轴

r - Shiny 的交互式 ggplot 缺少误差线

r - 基于字符串匹配过滤字符串向量

mysql - 如何使用 Shiny 的mysql表创建图形?