Mri*_*arg 6 r ggplot2 facet-wrap
我正在尝试使用 facet 更改 ggplot 图的标签,并且正在使用数据帧中未分面的变量。代码如下-
iris %>%
group_by(Species) %>%
summarise(lbl = mean(Petal.Length)) %>%
select(lbl) %>%
unlist() -> lbls
lbls <- map2(unique(iris$Species), lbls, paste, sep = "\n")
iris %>%
ggplot(aes(x = Sepal.Length, y = Sepal.Width, group = 1)) +
geom_point() +
facet_wrap(~ Species, labeller = lbls)
Run Code Online (Sandbox Code Playgroud)
但是,这给了我以下错误-
Error in cbind(labels = list(), list(`{`, if (!is.null(.rows) ||
!is.null(.cols)) { :
number of rows of matrices must match (see arg 2)
Run Code Online (Sandbox Code Playgroud)
我查看了 labeller 函数和不同的选项,但其中大多数似乎是针对包含在 facet 中的变量。有没有办法做到这一点?任何线索表示赞赏,谢谢!
您可以即时创建一个新的分面列并避免labeller痛苦:
iris %>%
group_by(Species) %>%
mutate(label = paste0(Species, "\n", round(mean(Petal.Length),2))) %>%
ggplot(aes(x = Sepal.Length, y = Sepal.Width, group = 1)) +
geom_point() +
facet_wrap(~ label)
Run Code Online (Sandbox Code Playgroud)
从文档中?labeller,labeller也可以是命名的字符向量。请注意,我们需要将字符向量包装在labeller函数中。同样通过查看帮助文件中的示例,我们需要将 facetting 变量Species作为参数传递给labeller. 因此调用应该类似于:
labeller = labeller(Species = setNames(unlist(lbls), unique(iris$Species)))
代码应该是:
iris %>%
ggplot(aes(x = Sepal.Length, y = Sepal.Width, group = 1)) +
geom_point() +
facet_wrap(~ Species, labeller = labeller(Species = setNames(unlist(lbls), unique(iris$Species))))
Run Code Online (Sandbox Code Playgroud)
此外,创建标签的更简洁的方法是没有map2:
lbls <- setNames(paste(unique(iris$Species), lbls, sep = "\n"), unique(iris$Species))