在map()中使用ggplot2,如何在sec_axis()的公式中引用对象?

时间:2018-04-04 07:23:43

标签: r ggplot2 purrr

我使用map()创建了ggplot2的图表。我想创建第二个y轴引用其他对象,但公式sec_axis()中的对象名称不在map()内解析。如何在公式sec_axis()中引用其他对象?

非常感谢任何帮助。下面是一个示例代码和输出:

library(tidyverse)
set.seed(1)
d <- data_frame(n = sample(500:1000, 15), 
                group = letters[rep(1:5, 3)],
                year = rep(2011:2013, each = 5)) %>% 
  nest(-year)

d <- d %>% 
  mutate(
    gg1 = map2(data, year, ~ {
      total <- sum(.x$n)
      ggplot(.x, aes(x = group, y = n)) +
        geom_bar(stat = "identity") +
        ggtitle(paste0("year = ", .y, "; total = ", total))  # no problem
    }),
    gg2 = map2(data, year, ~ {
      total <- sum(.x$n)
      ggplot(.x, aes(x = group, y = n)) +
        geom_bar(stat = "identity") +
        ggtitle(paste0("year = ", .y, "; total = ", total)) +
        scale_y_continuous(sec.axis = sec_axis(~ ./total))   # problem line
    }))

d$gg1[[1]]   # run
d$gg2[[1]]   # Error in eval(expr, data, expr_env) : object 'total' not found

enter image description here

1 个答案:

答案 0 :(得分:1)

感谢您的回复。我注意到formula()可以在sec_axis()内为map2()提供公式和解析对象。 (此方法无法解决map()中的问题,我认为这是因为.中的map()不明确

d <- d %>% 
  mutate(
    gg2 = map2(data, year, ~ {
      total <- sum(.x$n)
      ggplot(.x, aes(x = group, y = n)) +
        geom_bar(stat = "identity") +
        ggtitle(paste0("year = ", .y, "; total = ", total)) +
        scale_y_continuous(sec.axis = sec_axis(formula(paste0(" ~ ./", total))))
    }),
    gg3 = map(data, ~ {
      total <- sum(.x$n)
      ggplot(.x, aes(x = group, y = n)) +
        geom_bar(stat = "identity") +
        scale_y_continuous(sec.axis = sec_axis(formula(paste0(" ~ ./", total))))
    }))

d$gg2[[1]]  # run
d$gg3[[1]]  # Error in as.list.environment(x, all.names = TRUE) : 
            #  the ... list does not contain 2 elements

enter image description here