ggplotは aes
の中がNSEになっている。なので、
ggplot(data = iris) + geom_histogram(aes(x = Sepal.Length))
これは動くけど、
ggplot(data = iris) + geom_histogram(aes(x = 'Sepal.Length'))
これは動かない。文字列を aes
に引き渡したいときは、 aes_string
に置き換えて
ggplot(data = iris) + geom_histogram(aes_string(x = 'Sepal.Length'))
これなら動くようになる。
x =
に複数の変数を渡して、複数のggplotを出力したいときに便利
f_hist <- function(data, var) { p <- ggplot(data = data) + geom_histogram(aes_string(x = var)) ggsave( p, filename = str_c(var, '.jpg'), width = 8, height = 8, dpi = 300 ) } map( .x = c('Sepal.Length', 'Sepal.Width'), .f = ~ {f_hist(data = iris, var = .x)} )