I'm trying to change labels for ggplot graph with facets, and am using a variable from the dataframe which is not faceted. The code is as belows-
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)
However, this gives me the following error-
Error in cbind(labels = list(), list(`{`, if (!is.null(.rows) ||
!is.null(.cols)) { :
number of rows of matrices must match (see arg 2)
I've looked at the labeller function and different options but most of them seem to be for variables which are included in facets. Is there a way this can be done? Any leads appreciated, thanks!
From the documentation on ?labeller
, labeller
can also be a named character vector. Note that we need to wrap the character vector in the labeller
function. Also from looking at the examples in the help file, we need to pass the facetting variable Species
as the argument to labeller
. Thus the call should look something like:
labeller = labeller(Species = setNames(unlist(lbls), unique(iris$Species)))
The code should then be:
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))))
Also, a much cleaner way to create the labels would be without map2
:
lbls <- setNames(paste(unique(iris$Species), lbls, sep = "\n"), unique(iris$Species))
You could create a new facetting column on the fly and avoid labeller
pain:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With