绘图功能在lapply期间不会获取名称

时间:2018-01-27 19:46:32

标签: r ggplot2 lapply

我正试图让lapply访问我正在喂它的情节列表的名称。我看过其他一些看似非常相似的帖子,但仍不确定如何将列表名称的向量传递给它。

require(mlbench)
require(gridExtra)
require(dplyr)
require(ggplot2)

data(Soybean)

dfs <- lapply(Soybean, function(x) data.frame(table(x, exclude = NULL)))

display_charts <- function(x){
  ggplot(data.frame(x) %>% select(x = 1, y = 2), aes(x = x, y = y)) + 
    geom_col(col = 'red',
             fill = 'green',
             alpha = 0.3) +
    labs(title = names(x),
         x = names(x),
         y = 'Frequency')
}

all_charts <- lapply(dfs, display_charts)

n <- length(all_charts)
nCol <- floor(sqrt(n))
do.call("grid.arrange", c(all_charts, ncol=nCol))

我尝试调整lapply函数调整display_charts函数以接受name参数,并将names(x)替换为name,然后尝试调整nms <- names(dfs)函数创建名为seq_along(dfs), display_charts, x = dfs, nm = nms的名称向量,然后执行gcc -I ./curl-7.58.0/include/curl alexa_request_simple_demo.c -I ./cJSON-master -L ./cJSON-master/build ./libcjson.1.7.1.dylib ./libcurl.4.dylib 但它不起作用。

此图为数据集生成6x6频率图的网格,但我想将标题作为图的每个名称。我觉得这样看着我的脸,我看不到它。

1 个答案:

答案 0 :(得分:5)

而不是使用lapply迭代dfs遍历整个列表的列表,如果它包含:

# Replaced `all_charts <- lapply(dfs, display_charts)` with:
all_charts <- lapply(seq_along(dfs), function(i) display_charts(dfs[i]))

ggplot函数中的display_charts()输入使用x[[1]],因为它仍然是一个列表:

display_charts <- function(x) {
  library(ggplot2)
  ggplot(x[[1]] %>% select(x = 1, y = 2), aes(x = x, y = y)) + 
    geom_col(col = 'red',
             fill = 'green',
             alpha = 0.3) +
    labs(title = names(x),
         x = names(x),
         y = 'Frequency')
}

enter image description here