Search code examples
rvisualization

Optimize Code: Passing df twice in 1 plot & Months


I've written the below code using R on Rstudio.

# Calculate the current month as a numeric value
current_month <- as.numeric(format(Sys.Date(), "%m"))

# Create a sequence from 1 to the current month - 1
monthseq <- seq(1, current_month - 1)

# Convert these numbers to actual months in the current year
# Assuming we are using the current year for all months
current_year <- format(Sys.Date(), "%Y")
dates <- as.Date(paste(current_year, monthseq, "01", sep = "-"), "%Y-%m-%d")

# Format these dates to get abbreviated month names
month_list <- format(dates, "%b")

final_financials[is.na(final_financials)] <- 0 #changing all NA's to 0 to make it easier to report.

report <- final_financials %>% filter(Month %in% month_list &
                                        Segment == "Revenues")

png(filename = "figs/ActualVBudget.png") #init the file to save the plot
report %>%  ggplot(aes(Month, Actuals)) + geom_col() + geom_crossbar(
  data = report,
  aes(x = Month),
  y = report$Budget,
  ymin = report$Budget,
  ymax = report$Budget,
  color = "red"
)
dev.off() #closing and saving the file so I can access it

I am not happy with the way I worked around the months, but I want something scalable.

I am also not happy with the way I wrote the plot, since I had to pass data twice, is there a better way to do this?


Solution

  • You could simplify your code a little per below (using a some made-up data):

    library(tidyverse)
    
    # Made-up financials
    report <- 
      tribble(~Month, ~Actuals, ~Budget, ~Segment,
              "Jan", 10, 9, "Revenues",
              "Feb", 11, 11, "Revenues",
              "Mar", 12, NA, "Revenues",
              "Apr", 12, 13, "Revenues"
      )
    
    # Code
    months <- seq(
      ymd("2024-01-01"), 
      floor_date(today(), unit = "month") - months(1), 
      by = "month"
    ) |> format("%b")
    
    report |>
      mutate(across(c(Actuals, Budget), \(x) replace_na(x, 0))) |>
      filter(Month %in% months, Segment == "Revenues") |> 
      ggplot(aes(Month, Actuals)) +
      geom_col() +
      geom_crossbar(aes(y = Budget, ymin = Budget, ymax = Budget), color = "red")
    

    
    ggsave("ActualVBudget.png")
    #> Saving 7 x 5 in image
    

    Created on 2024-05-02 with reprex v2.1.0