在facet_wrap中命名构面

时间:2018-09-26 20:16:36

标签: r ggplot2 facet-wrap

我在尝试命名使用facet_wrap功能创建的一组绘图时遇到问题。我专门尝试将标题包装到多行上。我已在堆栈溢出中广泛研究了此问题,但找不到我正在生成的错误。代码如下。 a2 $ variable是一列字符串(出于分组目的),a2 $ ma_3和a2 $ ma_12是我尝试绘制的移动平均值。生成的错误是:

as.integer(n)中的错误:   无法将类型'closure'强制转换为类型'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))

先谢谢了。

2 个答案:

答案 0 :(得分:2)

我建议在将变量发送到ggplot之前先对其进行格式化,如下所示:

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

enter image description here

答案 1 :(得分:2)

您已经关闭。要修改facet_wrap标签,我们使用labeller参数:

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

输出:

enter image description here