Introduction to Creating a Mortgage Calculator Plot with Matplotlib
=====================================
In this article, we will delve into creating a mortgage calculator plot using Matplotlib. The goal is to visualize the “Principal Paid” and “Interest Paid” as lines on a graph, with the dollars on the x-axis and years/dates on the y-axis.
Understanding the Mortgage Calculator Code
The provided code calculates a fixed-rate mortgage using NumPy Financial’s functions for payments. It prompts the user for input values: the interest rate, number of years, payment frequency per year (e.g., monthly), loan amount, and start date.
import pandas as pd
import numpy_financial as npf
from datetime import date
def fixed_rate_mortgage(interest: float, years: int, payments_year: int, mortgage: int, start_date: str):
# Create a range of dates from the start date to the end of the year after completion
rng = pd.date_range(start_date, periods=years * payments_year, freq='MS')
rng.name = "Payment Date"
df = pd.DataFrame(index=rng, columns=['Payment', 'Principal Paid', 'Interest Paid', 'Ending Balance'], dtype='float')
# Reset the index to create a row number
df.reset_index(inplace=True)
# Add 1 to account for the first payment being at -1 * payments_year
df.index += 1
df.index.name = "Period"
# Calculate monthly interest rate from annual rate
monthly_interest_rate = (interest / 12) / (1 + (interest / 12)) ** years * payments_year
# Calculate the monthly payment amount
df["Payment"] = -1 * npf.pmt(monthly_interest_rate, payments_year, mortgage)
# Calculate interest paid for each month
df["Interest Paid"] = -1 * npf.ipmt(monthly_interest_rate, payments_year, df.index, payments_year, mortgage)
# Calculate principal paid for each month
df["Principal Paid"] = -1 * npf.ppmt(monthly_interest_rate, payments_year, df.index, payments_year, mortgage)
# Initialize ending balance to 0 and calculate the first payment amount
df.loc[1, "Ending Balance"] = mortgage - df.loc[1, "Principal Paid"]
# Update the ending balance for each period based on previous balances
df['Ending Balance'] = mortgage - df['Principal Paid'].cumsum()
# Ensure negative ending balances become 0 to avoid errors
df[df['Ending Balance'] < 0] = 0
return df
payments_year = 12
years = input("Write how many years \n")
years = float(years)
interest = input("Write the interest \n")
interest = float(interest)
loan = input("Write the amount you want to loan \n")
loan = float(loan)
start_date = input("What is the start date, put it in YYYY-MM-DD format")
year, month, day = map(int, start_date.split("-"))
start_date = date(year, month, day)
fixed_rate_mortgage(interest, years, payments_year, loan, start_date)
Creating the Mortgage Calculator Plot
The plot is created using Matplotlib’s plot
function. We define two variables for principal paid and interest paid values.
import matplotlib.pyplot as plt
x1 = df['Principal Paid']
x2 = df['Interest Paid']
y = df.index.map(date.toordinal)
plt.plot(x1,y,label="Principal Paid")
plt.plot(x2,y,label="Interest Paid")
# Add title to the plot
plt.title("Mortgage Calculator Plot")
# Show the legend
plt.legend()
# Display the plot
plt.show()
Note that this is a basic example. Matplotlib offers many options for customizing plots.
Customization Options
The following are some common customization options when working with Matplotlib:
- Axis labels: Adding axis labels to both the x-axis and y-axis using
ax.set_xlabel()
andax.set_ylabel()
- Title: Adding a title to the plot using
plt.title()
- Legend: Showing or hiding the legend by adding
plt.legend()
orplt.legend(None)
- Markers: Changing the line markers used in the plot by passing a marker symbol to
plt.plot()
, such asplt.plot(x,y,'o')
for circles - Color palette: Customizing the colors of different lines and/or points by using color codes (e.g.,
'r'
for red`) or RGB values - Gridlines: Adding gridlines to the plot using
ax.grid()
Common Matplotlib Functions
Matplotlib offers a wide range of functions that can be used to customize plots, including:
ax.set_title()
: Setting the title of an axis.ax.set_xlabel()
: Setting the label for the x-axis.ax.set_ylabel()
: Setting the label for the y-axis.ax.legend()
: Creating a legend.ax.grid()
: Adding gridlines to an axis.
Conclusion
In this article, we have explored how to create a mortgage calculator plot using Matplotlib. We began by understanding the basic structure of the provided code and then moved on to creating the plot itself. Additionally, we touched upon some common customization options available in Matplotlib, including titles, labels, legends, markers, colors, and gridlines.
Final Plot Code
import matplotlib.pyplot as plt
x1 = df['Principal Paid']
x2 = df['Interest Paid']
y = df.index.map(date.toordinal)
plt.plot(x1,y,label="Principal Paid")
plt.plot(x2,y,label="Interest Paid")
# Add title to the plot
plt.title("Mortgage Calculator Plot")
# Show the legend
plt.legend()
# Display the plot
plt.show()
Last modified on 2024-06-01