首页 > 解决方案 > 如何使用 R 创建用于制作 qqplots 的自动化/循环?

问题描述

是否可以进行自动化/循环以在数据框中制作数字列的 qqplots?

以下用于制作循环以使用 ggplot 创建直方图:

x %>% keep(is.numeric) %>% gather() %>% ggplot(aes(value)) +facet_wrap(~key, scales = "free") + geom_histogram()

但是用 qqplot 函数替换 geom_histogram 函数对于循环 qqplots 不起作用

x %>% keep(is.numeric) %>% gather() %>% ggplot(aes(value))+ geom_qq(mapping = NULL) +facet_wrap(~key, scales = "free")

我尝试过使用各种 qqplot 函数,但大多数都返回以下错误:

* Error: stat_qq requires the following missing aesthetics: sample Run `rlang::last_error()` to see where the error occurred.

<error/rlang_error>
stat_qq requires the following missing aesthetics: sample
Backtrace:
  1. (function (x, ...) ...
  2. ggplot2:::print.ggplot(x)
  4. ggplot2:::ggplot_build.ggplot(x)
  5. ggplot2:::by_layer(function(l, d) l$compute_statistic(d, layout))
  6. ggplot2:::f(l = layers[[i]], d = data[[i]])
  7. l$compute_statistic(d, layout)
  8. ggplot2:::f(..., self = self)
  9. self$stat$compute_layer(data, params, layout)
 10. ggplot2:::f(..., self = self)
 11. ggplot2:::check_required_aesthetics(...)
Run `rlang::last_trace()` to see the full context.```*




标签: ggplot2

解决方案


我的猜测是您需要将 qqplot 美学中的调用更改为:

ggplot(aes(sample = value))

以下代码适用于我:

x <- rnorm(100)

x %>% 
  keep(is.numeric) %>% 
  enframe(name = NULL) %>% 
  mutate(key = rep(c("cat1", "cat2"), 50)) %>% 
  ggplot(aes(x = value)) +
  geom_histogram() +
  facet_wrap(~ key, scales = "free")

x %>% 
  keep(is.numeric) %>% 
  enframe(name = NULL) %>% 
  mutate(key = rep(c("cat1", "cat2"), 50)) %>% 
  ggplot(aes(sample = value)) +
  geom_qq() +
  facet_wrap(~ key, scales = "free")

推荐阅读