I have a list of dataframes, each of which has a grouping variable. I want to plot a barchart for each dataframe and for each group and at the same time, so that the ggtitle of each chart matches the current dataframe name the value of the current grouping variable.
Minimal data for reproduce:
tmp <- list(
HLA_alpha_A = tibble(group_var = c(1, 1, 2, 2),
TR = c("TRAV21", "TRAV13", "TRAV26", "TRAV9"),
value = c(132530, 175940, 97014, 144928)),
HLA_alpha_B = tibble(group_var = c(7, 7, 9, 9),
TR = c("TRAV21", "TRAV13", "TRAV26", "TRAV9"),
value = c(113892, 181864, 112286, 149134)))
And my current code now:
tmp %>%
map(~ .x %>%
group_by(group_var) %>%
group_map(~ .x %>%
ggplot(aes(factor(reorder(TR, -value)), value))
geom_bar(stat="identity")
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
ylab("")
xlab("")
ggtitle(paste0(names(.x), " allele ", .y))))
So far it turns out like this:
I want the name of the dataframe, not the column, to be substituted, that is, for the first chart, the title should be HLA_alpha_A allele 1
CodePudding user response:
I think the key to solving this is not to use purrr style lambda functions, as the inner group_map()'s .y prevents you from accessing your df's name in the outer imap(). Luckily, R 4.1 introduced base lambda functions.
library(tidyverse)
tmp %>%
imap(\(d, dname) d %>%
group_by(group_var) %>%
group_map(\(dsub, grp) dsub %>%
ggplot(aes(factor(reorder(TR, -value)), value))
geom_bar(stat="identity")
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
ylab("")
xlab("")
ggtitle(paste0(dname, " allele ", grp))))
#> $HLA_alpha_A
#> $HLA_alpha_A[[1]]

#>
#> $HLA_alpha_A[[2]]

#>
#>
#> $HLA_alpha_B
#> $HLA_alpha_B[[1]]

#>
#> $HLA_alpha_B[[2]]

Created on 2022-01-29 by the reprex package (v2.0.1)
CodePudding user response:
Other solution:
plots <- mapply(function(xx, yy) {
print(xx %>%
group_by(group_var) %>%
group_map(~ .x %>%
ggplot(aes(factor(reorder(TR, -value)), value))
geom_bar(stat="identity")
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
ylab("")
xlab("")
ggtitle(paste0(yy, " allele ", .y))))
}, tmp, names(tmp))

