Reputation: 67
I am having issues trying to name a set of plots created with the facet_wrap feature. I am specifically trying to wrap the titles onto multiple lines. I have looked into this issue extensively within stack overflow and cannot find the error that I am generating. The code is below. a2$variable is a column of character strings (for grouping purposes), a2$ma_3 and a2$ma_12 are moving averages that I am trying to plot. The error that is generated is:
Error in as.integer(n) : cannot coerce type 'closure' to vector of type 'integer'
p1=a2 %>%
ggplot(aes(x = date, color = variable)) +
geom_line(aes(y = ma_12), color = "aquamarine3", alpha = 0.5,size=.7) +
geom_line(aes(y = ma_3), color = "gray40", alpha = 0.5,size=.7) +
facet_wrap(~ variable, ncol = 3, scale = "free_y",label_wrap_gen(width=10))
Thanks in advance.
Upvotes: 1
Views: 299
Reputation: 18661
You're close. To modify the facet_wrap
labels, we use the labeller
argument:
library(tibble)
library(ggplot2)
mtcars %>%
rownames_to_column() %>%
head() %>%
ggplot(aes(x = mpg, color = cly)) +
geom_point(aes(y = wt), color = "aquamarine3", alpha = 0.5,size=5) +
geom_point(aes(y = qsec), color = "gray40", alpha = 0.5,size=5) +
facet_wrap(~ rowname, ncol = 3, scale = "free_y",
labeller = label_wrap_gen(width = 10))
Output:
Upvotes: 2
Reputation: 66415
I'd suggest formatting the variable before you send it to ggplot, like this:
library(tidyverse)
mtcars %>%
rownames_to_column() %>%
head() %>%
mutate(carname = stringr::str_wrap(rowname, 10)) %>%
ggplot(aes(x = mpg, color = cly)) +
geom_point(aes(y = wt), color = "aquamarine3", alpha = 0.5,size=5) +
geom_point(aes(y = qsec), color = "gray40", alpha = 0.5,size=5) +
facet_wrap(~ carname, ncol = 3, scale = "free_y")
Upvotes: 2