Home > database >  How to plot varius plots in different figures from different variables of a dataframe with minimum c
How to plot varius plots in different figures from different variables of a dataframe with minimum c

Time:10-28

I wonder if there is a function in ggplot2 package or another package or a for-loop way in R to create different figures of plots from various variables/columns of a dataframe without coding every one, each figure for each variable. For example, if I have a dataframe called df with several columns: id (keys of data), v1, v2, ... v10. I would like to plot various variables (v2 to v8) in axis Y, with v1 in axis X, but not repeating the same code for every single variable.

    # For 1 plot, how could I code for various plots?    
         plot_v2 <- df%>% # (plot_name as column name, i.e plot_v2)
            ggplot( aes(x=v1, y=v2, group=id, 
                        color=id))  
              geom_line()
    # This code creates a figure with a plot, I want to know a way to do this for all 
    # variables v2 to v8 in axis Y, with a new figure for each one.

This is just a theorical question, any suggestion or hint about a function to look or a way to write the for-loop will be very helful. I can't provide any sample data. I tried once using a for loop but there are some issues when I have to specify the name of the variable for the axis in aes() as well as the name of the plot object. Really appreciate any help!

Because my first post asking this doubt happened to be closed, I'll make it clear, I don't want to plot all the variables in the same plot/figure, I want to know how to create a new figure for every variable. Something like in Matlab it would be using figure() function every time and iterating over the columns of a table.

PS: Whoever moderator who deleted my first post, I would appreciate if first you contact me or ask me in case you suggest the question was already posted, before deleting the post. Previously question suggested didn't help me. Thanks!

CodePudding user response:

Let's define an example dataframe

df <- data.frame(
  v1 = runif(40, min = 0, max = 20), 
  v2 = runif(40, min = -10, max = 10),
  v3 = runif(40, min = -30, max = 40),
  v4 = runif(40, min = -30, max = 40),
  v5 = runif(40, min = -30, max = 40),
  v6 = runif(40, min = -30, max = 40),
  v7 = runif(40, min = -30, max = 40),
  v8 = runif(40, min = -30, max = 40),
  id = rep(c("a", "b", "c", "d"), each = 10)
)

We can define a function that takes an index and the dataframe as input and generates a plot based on the index passed

# to change the selected columns, edit `[[i   1]]`
make_plot <- function(i, df) {
  df %>% 
    ggplot(aes(x = v1, y = .[[i   1]], color = id))  
    geom_line()
}

Finally we represent the plots by invoking the lapply function

lapply(1:7, make_plot, df)
  • Related