How to plot specific columns in multiple dataframes in a list?

Viewed 84

Sorry for this basic question. I thought I'd be able to solve this but I really could not figure out the syntax. I am quite new to R. Hopefully someone could explain to me how to do this.

I have a list of data frames with data and I wish to plot them.

df_list <- list(
  `1.3.A` = 
    tibble::tribble(
      ~Person, ~Height, ~Weight,
      "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L
    ),
  `2.2.A` = 
    tibble::tribble(
      ~Person, ~Height, ~Weight,
      "Missy",    175L,     75L,
      "Britany",    180L,     85L,
      "Sussie",    179L,     79L
    ), 
  `1.1.B` = 
    tibble::tribble(
      ~Person, ~Height, ~Weight,
      "Luke",    175L,     75L,
      "Alex",    180L,     85L,
      "Haley",    179L,     79L
    )
)

Is there a way to plot the Height and Weight columns using ggdensity(). I am trying to make multiple density plots of each columns (Height and Weight) of each data frames but failed to do it.

Some codes I tried:

make_hist <- function(x){
  ggdensity(data, x)
}
plots <- lapply(df_list, make_hist)

r <- lapply(df_list, function(x) {
  ggdensity(data, x)

I even tried using imap but could not figure out the proper syntax for ggdensity and wrap it with imap() function or lapply().

Really sorry for this basic question and I hope someone could explain me the answer.

1 Answers

We can loop over the 'df_list', create the density plots for both 'Height' and 'Weight', then flatten the nested list (do.call(c) and use ggarrange to plot the elements in the list by specifying the nrow and ncol

library(ggpubr)
plots <- lapply(df_list, function(x) ggdensity(x, c("Height", "Weight")))
plots1 <- do.call(c, plots)
ggarrange(plotlist = plots1, nrow = 3, ncol = 2)

-output

enter image description here

Related