Home > database >  How can I create multiple plots from same dataset in R?
How can I create multiple plots from same dataset in R?

Time:10-17

Let me first share a dummy data, from which I want to prepare ggplot graphs.

library(tidyverse)
set.seed(1)
sample_size <- 1200
dates <- sample(seq(1,31),sample_size,replace = TRUE)
Monthss <- sample(seq(1,12),sample_size,replace = TRUE)
hrs <- sample(seq(1,23),sample_size,replace = TRUE)
minutes <- sample(seq(1,59),sample_size,replace = TRUE)
date_time_vector <- paste0(dates,"-",Monthss,"-",2022," ",hrs,":",minutes) |> lubridate::parse_date_time("dmy HM")
Conversion <- sample(c(TRUE,FALSE),sample_size, prob = c(0.25,0.75), replace = TRUE)
df <- data.frame(Date = date_time_vector, Conversion_Status = Conversion)
df <- df |> mutate(Leads = round(runif(sample_size, min = 0,max = 10),digits = 0))
df <- df[complete.cases(df), ]

The code above gives me a data.frame with columns Date, Leads and Conversion_Status. I want to prepare Monthly column chart of total leads per day. (For example, daily leads in January, daily leads in February, etc.) So, basically, I will need to split the data on the basis of Month, and prepare one chart for each month. How can I prepare such charts?

I have tried following way:

bar_function <- function(df, col1, col2, title) {
  df %>% 
    ggplot2::ggplot(aes(x = {{col1}}, y = {{col2}}))  
    ggplot2::geom_col(fill = "steelblue")  
    theme(plot.background = element_rect(fill = "white"))  theme(plot.title = element_text(hjust = 0.5)) coord_flip()  
    ggplot2::labs(title = title)
}
mycharts <- df |> dplyr::nest_by(Month) |> dplyr::mutate(plot = bar_function(df,Date,Leads,"Daily Leads by Month"))

But it is giving me errors.

CodePudding user response:

You can split according to month(year) and plot that.

library(ggplot2)
library(lubridate)

set.seed(1)
sample_size <- 1200
dates <- sample(seq(1,31),sample_size,replace = TRUE)
Monthss <- sample(seq(1,12),sample_size,replace = TRUE)
hrs <- sample(seq(1,23),sample_size,replace = TRUE)
minutes <- sample(seq(1,59),sample_size,replace = TRUE)
date_time_vector <- paste0(dates,"-",Monthss,"-",2022," ",hrs,":",minutes) |> lubridate::parse_date_time("dmy HM")
Conversion <- sample(c(TRUE,FALSE),sample_size, prob = c(0.25,0.75), replace = TRUE)
df <- data.frame(Date = date_time_vector, Conversion_Status = Conversion)
df$Leads <- round(runif(sample_size, min = 0,max = 10),digits = 0)
df <- df[complete.cases(df), ]

df$month_year <- strftime(df$Date, format = "%m-%Y")

df.split <- split(df, f = df$month_year)
out <- vector("list", length(df.split))
names(out) <- names(df.split)

for (i in seq_along(df.split)) {
  out[[i]] <- ggplot(data = df.split[[i]], mapping = aes(x = Date, y = Leads))  
    geom_col(fill = "steelblue")  
    theme(plot.background = element_rect(fill = "white"))  
    theme(plot.title = element_text(hjust = 0.5)) 
    coord_flip()  
    labs(title = "Daily leads by month")
}

To plot you can just print e.g. out[[1]].

If you want to change the desired columns dynamically, you can use aes_string for mapping. This can naturally be wrapped into sapply and there are probably other ways of approaching the problem. The for loop is pretty agnostic and I find that it's readable even by people who do not dabble in R (compared to say sapply).

CodePudding user response:

There are some issues with your code. First, your dataset has no Month column, i.e. you have to add it for which I use lubridate::month. Second, you are passing the dataset df to your bar function instead of the splitted data column from your nested df. Third, in the mutate step you have to wrap the result in list():

library(ggplot2)
library(dplyr, warn=FALSE)

mycharts <- df |>
  nest_by(Month = lubridate::month(Date)) |>
  mutate(plot = list(bar_function(data, Date, Leads, "Daily Leads by Month")))

mycharts$plot[[1]]


mycharts$plot[[5]]

  • Related