问题
I've used R for a while now, and still don't know what I'm doing when it comes to using facet_wrap()
. Consider this, for exapmle:
ggplot(df, aes(x, y)) +
geom_bar(stat = "identity") +
facet_wrap(~ z)
It works, but whenever I use facet_wrap()
I end up just trying different permutations of how its argument should be formatted. This is because I have no idea what ~
or .
mean in these arguments.
Does anyone have a succinct description of what these things are?
回答1:
The facet_grid
docs state:
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). The formula can also be provided as a string instead of a classical formula object
facet_wrap
docs state:
Either a formula or character vector. Use either a one sided formula, ~a + b, or a character vector, c("a", "b").
The examples in both help pages are designed to illustrate what's going on, but you can mock up your own examples to see what the differences are. e.g.:
library(ggplot2)
gg <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
gg + facet_wrap(~cyl)
gg + facet_wrap("cyl")
gg + facet_wrap(~gear)
gg + facet_wrap("gear")
gg + facet_wrap(gear~cyl)
gg + facet_wrap(c("gear", "cyl"))
gg + facet_wrap(cyl~gear)
gg + facet_wrap(c("cyl", "gear"))
That's the best way to get a mental association with the idiom IMO.
来源:https://stackoverflow.com/questions/39148454/what-do-and-indicate-in-a-facet-wrap-argument