【问题标题】:facet_wrap() in ggplot with a combination of math expressions and a stringggplot 中的 facet_wrap() 结合了数学表达式和字符串
【发布时间】:2019-07-31 11:59:03
【问题描述】:

我有一个包含单个连续变量 (x) 和一个分类变量 (id) 的数据框。数据生成如下:

library(tidyverse)
df <- tibble(id = rep(1:9, each = 50), x = rnorm(450)) %>%
    mutate(id = replace(id, id == 9, "BLA"))

我正在考虑的情节是使用以下代码行生成的:

ggplot(df, aes(x = x)) +
    geom_histogram() +
    facet_wrap(~ id, labeller = labeller(id = facet_names))

facet_names 对象被定义为映射向量:

facet_names <- c(
    `1` = expression(i[1]),
    `2` = expression(i[2]),
    `3` = expression(i[3]),
    `4` = expression(i[4]),
    `5` = expression(i[5]),
    `6` = expression(i[6]),
    `7` = expression(i[7]),
    `8` = expression(i[8]),
    `9` = "BLA"
)

我想知道如何将facet_wrap 调用中的标签格式化为 i1, i2, ..., i8 , BLA

但是,在当前设置中,标签被绘制为 1、2、...、BLA(即,没有字母“i”和下标中的数字)。

感谢您的指点。

【问题讨论】:

    标签: r ggplot2 expression facet-wrap


    【解决方案1】:

    一种方法是将id 转换为facet_names 中指定水平的因子,然后使用label_parsed 作为标注函数,将标签解释为绘图表达式:

    library(dplyr)
    library(ggplot2)
    
    df <- mutate_at(df, .vars = "id", .funs = factor, labels = facet_names)
    
    ggplot(df, aes(x = x)) +
        geom_histogram() +
        facet_wrap(~ id, labeller = label_parsed)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-17
      • 2012-05-29
      • 2015-12-03
      • 1970-01-01
      相关资源
      最近更新 更多