Skip to contents

1. add_expense

Purpose: add a new entry to the data frame that tracks expenses.

Parameters

  • category: string describing the type of expense (e.g., “Groceries”, “Utilities”).

  • amount: monetary value of the expense.

  • expenses_data: reactive value that contains a data frame of expenses.

  • selected_categories: reactive value storing a list of categories that have already been selected.

  • session: Shiny session object, used for showing modal dialogues in the Shiny app.

Functionality

  1. Validate Amount:

    • The function first checks if the amount is NA (not available/missing) or less than 0. If either is true, a modal dialog box is displayed to the user, indicating that the amount must be non-negative, and the function returns FALSE.
  2. Check Category and Update Data:

    • The function then checks if the category is not already present in selected_categories. If it’s a new category, the function proceeds to add the expense.

    • It appends the new expense data (category and amount) to the current expenses_data data frame using rbind.

    • The expenses_data reactive value is updated with this new data frame.

    • The selected_categories reactive value is also updated to include the new category.

    • The function returns TRUE to indicate that the expense was successfully added.

  3. Handle Duplicate Category:

    • If the category already exists in selected_categories, the function does not add the expense and returns FALSE.

Example

In a Shiny app, this function would be used within an observeEvent or similar reactive context. It is triggered by a user action, specifically pressing an “Add Expense” button. The function reads the category and amount from the user input, attempts to add the expense, and then you can take additional actions based on whether the expense was successfully added.

# Load the Shiny package
if (!require(shiny)) install.packages("shiny")
#> Loading required package: shiny
#> Warning: package 'shiny' was built under R version 4.3.1
library(shiny)

# Assuming you have a Shiny reactive environment set up

# Initialize reactive values
expenses_data <- reactiveVal(data.frame(category = character(), amount = numeric()))
selected_categories <- reactiveVal(character())

# Example usage within a Shiny observeEvent
observeEvent(input$add_expense, {
  result <- add_expense(input$category, input$expense, expenses_data, selected_categories)
  if (result) {
    # Perform actions after successful addition
    print("Expense added successfully.")
  } else {
    # Handle cases where addition fails
    print("Failed to add expense.")
  }
})

2. generate_bar_chart

Purpose: creates a bar chart for visualizing data such as income, expenses, and savings.

Parameters

  • data: data frame that contains the data to be plotted. This data frame is expected to have at least two columns:

    • category: A column that contains the names of the categories (like “Income”, “Expenses”, “Savings”).

    • amount: A column that contains numerical values associated with each category.

  • colorblind_switch: A logical flag (TRUE or FALSE) that, when set to TRUE, enables a colorblind-friendly color palette for the bar chart. This is important for accessibility, ensuring that the visualization is readable by individuals with color vision deficiencies.

Functionality

  • Bar Chart Creation:

    • The function uses ggplot2 to create a basic bar chart. The aes function specifies the aesthetics of the plot, mapping category to the x-axis and amount to the y-axis.

    • geom_bar(stat = "identity") tells ggplot2 to create a bar chart where the heights of the bars represent the amount values in the data.

  • Color Palette:

    • Depending on the colorblind_switch, it selects a color palette that is either standard or colorblind-friendly. This is done using scale_fill_manual(values = color_palette).
  • Styling and Labels:

    • The chart is further styled with titles and labels using labs, and a minimal theme is applied for a clean, modern look (theme_minimal()). The legend is removed for simplicity.
  • Plotly Conversion:

    • Finally, ggplotly(p) converts the ggplot object into a Plotly object. This step enhances the interactivity of the plot, allowing for features like hover effects in a web-based environment.

Example

  • In a Shiny application, this plot can be rendered using renderPlotly() to make it interactive.
# Sample data
data <- data.frame(
  category = c("Income", "Expenses", "Savings"),
  amount = c(1000, 750, 250)
)

# Generate and display the bar chart
bar_chart <- generate_bar_chart(data, colorblind_switch = FALSE)
bar_chart

Output

  • The function returns a Plotly ggplot object, which is an interactive plot that can be rendered in a web browser, making it suitable for Shiny applications or R Markdown documents.

3. generate_comparison_plot

Function: visualize and compare two sets of financial data – the user’s expenses and the average expenses in Switzerland – in a scatter plot format. Provides insights into how personal spending patterns align with or deviate from national averages.

Parameters

  • user_vs_swiss: A data frame that contains the data for comparison. This data frame should have three columns:

    • category: Categories of expenses (like “Food”, “Transport”, “Utilities”).

    • user_amount: The amount of money spent by the user in each category.

    • swiss_amount: The average amount spent in each category in Switzerland.

  • colorblind_switch: A logical flag that determines whether the plot should use a colorblind-friendly color palette. This enhances accessibility for users with color vision deficiencies.

Functionality

  • Data Visualization:

    • The function uses ggplot2 to create a scatter plot. It plots both user_amount and swiss_amount as points on the plot, where each point’s position is determined by its relative share in the total expenses and its absolute amount.

    • The geom_point function is used twice to plot points for both user expenses and Swiss average expenses on the same graph, differentiated by shapes (“User” vs. “Swiss”).

  • Color Palette:

    • Depending on the colorblind_switch, it selects an appropriate color palette (brewer.pal) that is either standard or friendly for colorblind users.
  • Styling and Labels:

    • The chart is styled with titles, labels, and minimal themes for a clean appearance. The legend is positioned to the right for clarity.

    • The x-axis represents the percentage share of each category’s expenses relative to the total, and the y-axis represents the actual amount spent.

  • Plotly Conversion:

    • ggplotly(p) converts the ggplot object into a Plotly object, making the plot interactive. This interactivity enhances user engagement, allowing for features like tooltips on hover.

Example Usage

  • Just like the previous ones, this function is intended to be used within a Shiny server function.
# Sample data for user expenses vs. average expenses
user_vs_swiss <- data.frame(
  category = rep(c("Food", "Transport", "Utilities"), 2),
  amount = c(200, 150, 100, 250, 180, 120),
  type = c(rep("User's Expenses", 3), rep("Swiss Average Expenses", 3)),
  hover_text = c("Food: 200", "Transport: 150", "Utilities: 100", "Food: 250", "Transport: 180", "Utilities: 120")
)

# Generate the comparison scatter plot
colorblind_switch <- FALSE  # Set the colorblind mode
comparison_plot <- generate_comparison_plot(user_vs_swiss, colorblind_switch)

# Display the plot
comparison_plot

Output

  • The function returns a Plotly ggplot object, which is an interactive plot suitable for web applications, particularly for Shiny.

4. generate_scatter_or_pie

Purpose: to dynamically generate a visualization of expenses data, either as a scatter plot or a pie chart, based on user input.

  • Adaptive Visualization: The function can switch between two types of plots, offering flexibility in how the data is presented.

Parameters

  • expenses_data_summary: A data frame containing summarized expense data. It should have at least two columns:

    • category: The names of expense categories.

    • percentage: The percentage share of each category in the total expenses.

    • (The function seems to also use an amount column, as indicated in the scatter plot creation code.)

  • scatter_plot_type: A character string that specifies the type of plot to generate. It can be either “Scatter Plot” or “Pie Chart”. This parameter allows the function to switch between plot types based on user preference.

  • colorblind_switch: A logical value that, when true, switches the color palette to a colorblind-friendly mode. This enhances accessibility for users with color vision deficiencies.

Functionality

  1. Color Palette Selection:

    • Based on the colorblind_switch, the function selects a suitable color palette using brewer.pal.
  2. Creating the Scatter Plot:

    • If scatter_plot_type is “Scatter Plot”, the function creates a scatter plot using ggplot2.

    • The scatter plot represents each expense category as a point, with its position determined by the percentage share (x-axis) and the actual amount (y-axis).

    • Additional features like point color, size, and labels are added for clarity and aesthetics.

    • The scatter plot is then converted to an interactive Plotly plot using ggplotly.

  3. Creating the Pie Chart:

    • If scatter_plot_type is “Pie Chart”, the function uses Plotly’s plot_ly to create a pie chart.

    • The pie chart shows the proportion of each expense category in the total expenses.

    • It includes features like labels, percentages, and hover information.

Example

  • The function can be called within a Shiny server function, where the user’s choice of plot type and colorblind mode can be passed as inputs. The resulting plot can be rendered in the UI using renderPlotly.
# Packages
suppressPackageStartupMessages({
  library(ggplot2)
  library(plotly)
  library(RColorBrewer)
  library(magrittr)
})


# Dataframe
expenses_summary <- data.frame(
  category = c("Food", "Transport", "Utilities"),
  amount = c(200, 150, 100),
  percentage = c(40, 30, 30))

# Generate a pie chart
pie_chart <- generate_scatter_or_pie(expenses_summary, "Pie Chart", FALSE)
pie_chart