2

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.

4
  • In the make_hist function, what is data parameter Commented Aug 19, 2021 at 17:34
  • A density plot is a univariate plot. What do you mean when you say you want to make a density plot using height and height exactly? How many plots are you expecting in the output? Commented Aug 19, 2021 at 17:36
  • according to ggdensity() documentation, it should be the dataframe. Commented Aug 19, 2021 at 17:36
  • @MrFlick, I am trying to make 6 different plots, 2 for each data frame in the list Commented Aug 19, 2021 at 17:37

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is amazing! So every time I want to run a function, I just need to bind the column names?
The x is variable to be drawn. which can be a single column name or a vector of ones, whereas the y is by default ..density..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.