简体   繁体   中英

naming facets in facet_wrap

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.

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")

在此处输入图片说明

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM