Reputation: 3722
I'm trying to allow lapply to access the names of the list of plots that I'm feeding it. I have looked at a few other posts that seem very similar but still not sure how to pass it the vector of names of my list.
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))
I have tried to adjust the lapply
function by adjusting the display_charts
function to accept a name
argument, and replacing names(x)
with name
, and then creating a vector of names called nms <- names(dfs)
, and then doing seq_along(dfs), display_charts, x = dfs, nm = nms
but it doesn't work.
This plot produces a 6x6 grid of frequency plots for the dataset, but I would like to have the title be each name of the plot. I feel like this is looking me square in the face, and I can't see it.
Upvotes: 4
Views: 171
Reputation: 28329
Instead of using lapply
to iterate over list of dfs
iterate over the length if it with:
# Replaced `all_charts <- lapply(dfs, display_charts)` with:
all_charts <- lapply(seq_along(dfs), function(i) display_charts(dfs[i]))
And for ggplot
input in display_charts()
function use x[[1]]
as it's still a list:
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')
}
Upvotes: 5