在地图函数中迭代应用 ggplot 函数
iteratively apply ggplot function within a map function
我想为数据集中的所有变量生成一系列直方图,但我显然没有正确准备数据以用于 map 函数。
library(tidyverse)
mtcars %>%
select(wt, disp, hp) %>%
map(., function(x)
ggplot(aes(x = x)) + geom_histogram()
)
我可以用 for 循环完成这个任务(h/t 但我正试图在 tidyverse 中做同样的事情。
foo <- function(df) {
nm <- names(df)
for (i in seq_along(nm)) {
print(
ggplot(df, aes_string(x = nm[i])) +
geom_histogram())
}
}
mtcars %>%
select(wt, disp, hp) %>%
foo(.)
非常感谢任何帮助。
要使用purrr::map
,您可以融化数据框,然后根据变量名将其拆分为数据框列表
library(reshape2)
library(dplyr)
library(ggplot2)
library(purrr)
melt(mtcars) %>%
split(.$variable) %>%
map(., ~ggplot(.x, aes(x=value)) +
geom_histogram())
您也可以使用ggplot2::facet_wrap
一次绘制它们
library(reshape2)
library(dplyr)
library(ggplot2)
melt(mtcars) %>%
ggplot(., aes(x=value, label=variable)) +
geom_histogram() +
facet_wrap(~variable, nrow=ncol(mtcars))
类似这样的方法也可以:
library(purrr)
library(dplyr)
mtcars %>%
select(wt, disp, hp) %>%
names() %>%
map(~ggplot(mtcars, aes_string(x = .)) + geom_histogram())
或:
mtcars %>%
select(wt, disp, hp) %>%
{map2(list(.), names(.), ~ ggplot(.x, aes_string(x = .y)) + geom_histogram())}
我想为数据集中的所有变量生成一系列直方图,但我显然没有正确准备数据以用于 map 函数。
library(tidyverse)
mtcars %>%
select(wt, disp, hp) %>%
map(., function(x)
ggplot(aes(x = x)) + geom_histogram()
)
我可以用 for 循环完成这个任务(h/t 但我正试图在 tidyverse 中做同样的事情。
foo <- function(df) {
nm <- names(df)
for (i in seq_along(nm)) {
print(
ggplot(df, aes_string(x = nm[i])) +
geom_histogram())
}
}
mtcars %>%
select(wt, disp, hp) %>%
foo(.)
非常感谢任何帮助。
要使用purrr::map
,您可以融化数据框,然后根据变量名将其拆分为数据框列表
library(reshape2)
library(dplyr)
library(ggplot2)
library(purrr)
melt(mtcars) %>%
split(.$variable) %>%
map(., ~ggplot(.x, aes(x=value)) +
geom_histogram())
您也可以使用ggplot2::facet_wrap
一次绘制它们
library(reshape2)
library(dplyr)
library(ggplot2)
melt(mtcars) %>%
ggplot(., aes(x=value, label=variable)) +
geom_histogram() +
facet_wrap(~variable, nrow=ncol(mtcars))
类似这样的方法也可以:
library(purrr)
library(dplyr)
mtcars %>%
select(wt, disp, hp) %>%
names() %>%
map(~ggplot(mtcars, aes_string(x = .)) + geom_histogram())
或:
mtcars %>%
select(wt, disp, hp) %>%
{map2(list(.), names(.), ~ ggplot(.x, aes_string(x = .y)) + geom_histogram())}