1. add_expense
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
-
Validate Amount:
- The function first checks if the
amount
isNA
(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 returnsFALSE
.
- The function first checks if the
-
Check Category and Update Data:
The function then checks if the
category
is not already present inselected_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 usingrbind
.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.
-
Handle Duplicate Category:
- If the category already exists in
selected_categories
, the function does not add the expense and returnsFALSE
.
- If the category already exists in
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
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. Theaes
function specifies the aesthetics of the plot, mappingcategory
to the x-axis andamount
to the y-axis.geom_bar(stat = "identity")
tellsggplot2
to create a bar chart where the heights of the bars represent theamount
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 usingscale_fill_manual(values = color_palette)
.
- Depending on the
-
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.
- The chart is further styled with titles and labels using
-
Plotly Conversion:
- Finally,
ggplotly(p)
converts theggplot
object into a Plotly object. This step enhances the interactivity of the plot, allowing for features like hover effects in a web-based environment.
- Finally,
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
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 bothuser_amount
andswiss_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.
- Depending on the
-
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 theggplot
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
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
-
Color Palette Selection:
- Based on the
colorblind_switch
, the function selects a suitable color palette usingbrewer.pal
.
- Based on the
-
Creating the Scatter Plot:
If
scatter_plot_type
is “Scatter Plot”, the function creates a scatter plot usingggplot2
.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
.
-
Creating the Pie Chart:
If
scatter_plot_type
is “Pie Chart”, the function uses Plotly’splot_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