Sort and rename facet labels in ggplot2

使用ggplot2作图时,对facet的label进行排序和重命名。

Sort

把含有labels的列转换为factor,并设定它的level,ggplot2就会自动按照level来排序。

1
2
n <- n %>%
mutate(strength = factor(strength, levels = c("S", "M", "W")))

Rename

创建一个named vector,把原来的label对应到name上,然后再作图的时候使用labeller函数。

1
2
3
4
5
6
7
8
ss_labels <- c(S = "Strong", M = "Medium", W = "Weak")

p <- (
ggplot(n, aes(...))
+ geom_col(position = position_dodge())
+ facet_wrap(~strength, labeller = labeller(strength = ss_labels))
...
)

References

1. https://stackoverflow.com/questions/14262497/fixing-the-order-of-facets-in-ggplot
2. http://www.cookbook-r.com/Graphs/Facets_(ggplot2)/