Calculating Weighted Average Interest Rate in Excel

Calculating Weighted Average Interest Rate in Excel – Free Calculator :root { –primary-color: #004a99; –success-color: #28a745; –background-color: #f8f9fa; –text-color: #333; –secondary-text-color: #666; –border-color: #ccc; –card-background: #fff; –shadow-color: rgba(0, 0, 0, 0.1); } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: var(–text-color); background-color: var(–background-color); margin: 0; padding: 20px; display: flex; flex-direction: column; align-items: center; } .container { width: 100%; max-width: 960px; background-color: var(–card-background); padding: 30px; border-radius: 8px; box-shadow: 0 4px 15px var(–shadow-color); margin-bottom: 40px; } h1, h2, h3 { color: var(–primary-color); margin-bottom: 20px; } h1 { font-size: 2.5em; text-align: center; margin-bottom: 10px; } .subtitle { text-align: center; color: var(–secondary-text-color); font-size: 1.1em; margin-bottom: 30px; } .loan-calc-container, .results-container, .formula-explanation, .example-section, .factors-section, .faq-section, .related-tools-section { margin-bottom: 40px; padding: 25px; border: 1px solid var(–border-color); border-radius: 8px; background-color: var(–card-background); } .loan-calc-container h2, .results-container h2, .formula-explanation h2, .example-section h2, .factors-section h2, .faq-section h2, .related-tools-section h2 { margin-top: 0; text-align: center; border-bottom: 2px solid var(–primary-color); padding-bottom: 10px; } .input-group { margin-bottom: 20px; display: flex; flex-direction: column; } .input-group label { font-weight: bold; margin-bottom: 8px; color: var(–primary-color); display: block; } .input-group input[type="number"], .input-group select { padding: 10px; border: 1px solid var(–border-color); border-radius: 4px; font-size: 1em; transition: border-color 0.3s ease; width: calc(100% – 22px); /* Adjust for padding */ } .input-group input[type="number"]:focus, .input-group select:focus { border-color: var(–primary-color); outline: none; box-shadow: 0 0 0 2px rgba(0, 74, 153, 0.2); } .input-group .helper-text { font-size: 0.85em; color: var(–secondary-text-color); margin-top: 5px; } .input-group .error-message { color: red; font-size: 0.8em; margin-top: 5px; height: 1.2em; /* Reserve space for message */ } .button-group { display: flex; justify-content: space-between; margin-top: 25px; gap: 10px; } button { padding: 12px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 1em; font-weight: bold; transition: background-color 0.3s ease, transform 0.2s ease; color: white; } button.primary { background-color: var(–primary-color); } button.primary:hover { background-color: #003366; transform: translateY(-1px); } button.secondary { background-color: #6c757d; } button.secondary:hover { background-color: #5a6268; transform: translateY(-1px); } button.success { background-color: var(–success-color); } button.success:hover { background-color: #218838; transform: translateY(-1px); } .results-container { text-align: center; } .results-container h2 { border-bottom: none; margin-bottom: 20px; } .result-summary { background-color: var(–primary-color); color: white; padding: 20px; border-radius: 8px; margin-bottom: 25px; display: inline-block; /* Allows background to fit content */ min-width: 80%; } .result-summary h3 { margin: 0 0 10px 0; color: white; font-size: 1.5em; } .result-summary p { margin: 0; font-size: 1.2em; } .intermediate-results, .formula-explanation, .key-factors, .faq-section, .related-tools-section { margin-top: 25px; } .intermediate-results div, .key-factors div, .faq-section article { margin-bottom: 15px; } .intermediate-results span, .key-factors span { font-weight: bold; color: var(–primary-color); } .chart-container { width: 100%; max-width: 700px; margin: 20px auto; background-color: var(–card-background); padding: 20px; border: 1px solid var(–border-color); border-radius: 8px; box-shadow: 0 2px 10px var(–shadow-color); } .chart-container h3 { text-align: center; margin-top: 0; margin-bottom: 15px; } table { width: 100%; border-collapse: collapse; margin-top: 20px; } th, td { padding: 12px; text-align: left; border-bottom: 1px solid var(–border-color); } thead th { background-color: var(–primary-color); color: white; font-weight: bold; } tbody tr:nth-child(even) { background-color: #f2f2f2; } caption { font-size: 0.9em; color: var(–secondary-text-color); margin-top: 10px; caption-side: bottom; text-align: center; } .section-title { font-size: 1.8em; color: var(–primary-color); margin-top: 30px; margin-bottom: 15px; border-bottom: 2px solid var(–primary-color); padding-bottom: 5px; } .section-content { margin-bottom: 25px; } .section-content p { margin-bottom: 15px; } .section-content ul, .section-content ol { padding-left: 20px; margin-bottom: 15px; } .section-content li { margin-bottom: 8px; } a { color: var(–primary-color); text-decoration: none; } a:hover { text-decoration: underline; } .faq-question { font-weight: bold; color: var(–primary-color); margin-bottom: 5px; } .related-tools-section ul { list-style: none; padding-left: 0; } .related-tools-section li { margin-bottom: 15px; } .related-tools-section strong { display: block; margin-bottom: 5px; } @media (max-width: 768px) { body { padding: 10px; } .container { padding: 20px; } h1 { font-size: 2em; } .button-group { flex-direction: column; gap: 15px; } button { width: 100%; } }

Calculating Weighted Average Interest Rate in Excel

Understand the blended cost of your various financial obligations or investments.

Weighted Average Interest Rate Calculator

Enter the principal amount for the first loan/debt.
Enter the annual interest rate for the first loan (e.g., 4.5 for 4.5%).
Enter the principal amount for the second loan/debt.
Enter the annual interest rate for the second loan.
Enter the principal amount for the third loan/debt.
Enter the annual interest rate for the third loan.

Calculation Results

Weighted Average Interest Rate

Total Principal Amount:

Total Interest Paid (Annualized):

Average Interest Rate (Simple):

How It's Calculated

The weighted average interest rate is calculated by summing the product of each loan's principal amount and its interest rate, then dividing by the total principal amount across all loans. This gives you the blended interest rate, reflecting the true cost of borrowing across multiple debts.

Formula: ( (P1 * R1) + (P2 * R2) + (P3 * R3) + … ) / ( P1 + P2 + P3 + … )

Where P = Principal Amount and R = Interest Rate for each loan.

Loan Principal Distribution

Distribution of loan principal amounts.

Loan Details Summary

Loan Principal Amount ($) Interest Rate (%) Annual Interest ($) Weight (%)
Loan 1
Loan 2
Loan 3
Total 100.00%

What is Weighted Average Interest Rate?

The weighted average interest rate is a crucial financial metric that represents the average interest rate across a collection of loans or investments, where each rate is weighted by its corresponding principal amount. Unlike a simple average, the weighted average gives more importance to larger loan amounts. This metric is essential for individuals and businesses managing multiple debts or diverse investment portfolios to understand their overall borrowing cost or investment yield.

Who Should Use It:

  • Individuals with multiple loans (mortgages, car loans, personal loans, credit cards).
  • Businesses managing various lines of credit, business loans, or bonds.
  • Investors holding bonds or other fixed-income securities with different coupon rates.
  • Financial analysts assessing portfolio risk and return.

Common Misconceptions:

  • It's the same as a simple average: A simple average would treat each loan equally, regardless of its size. The weighted average accurately reflects the impact of larger principal amounts.
  • It only applies to loans: While most commonly used for debts, the concept can be applied to investments to find the average yield of a portfolio.
  • It's overly complex to calculate: While it requires careful calculation, especially with many entries, tools like our calculator and Excel make it accessible.

Weighted Average Interest Rate Formula and Mathematical Explanation

The calculation of the weighted average interest rate is straightforward once you understand the concept of weighting. Each loan's contribution to the average is proportional to its size (principal amount).

Step-by-Step Derivation:

  1. Calculate the annual interest paid for each loan: For each loan (or investment), multiply its principal amount (P) by its interest rate (R). Note that the interest rate should be in decimal form (e.g., 4.5% becomes 0.045). The formula for annual interest is: Annual Interest = Principal * Rate.
  2. Sum the annual interest paid across all loans: Add up the annual interest amounts calculated in step 1 for all your loans. This gives you the total annual interest paid on your entire portfolio of debts.
  3. Sum the principal amounts of all loans: Add up the principal amounts for all loans. This gives you the total amount borrowed.
  4. Calculate the weighted average interest rate: Divide the total annual interest paid (from step 2) by the total principal amount (from step 3). This yields the weighted average interest rate.

Formula Summary:

Weighted Average Interest Rate = ∑(Principali * Ratei) / ∑(Principali)

Where:

  • ∑ denotes summation.
  • Principali is the principal amount of the i-th loan.
  • Ratei is the annual interest rate of the i-th loan (expressed as a decimal).

Variables Table:

Variable Meaning Unit Typical Range
Pi Principal Amount of Loan i Currency ($) > 0
Ri Annual Interest Rate of Loan i % or Decimal 0.01% – 50%+ (depending on loan type)
∑(Pi * Ri) Total Annual Interest Paid Across All Loans Currency ($) Varies greatly
∑(Pi) Total Principal Amount Across All Loans Currency ($) > 0
Weighted Average Interest Rate Blended Annual Interest Rate of the Portfolio % Between the lowest and highest Ri

Practical Examples (Real-World Use Cases)

Example 1: Managing Personal Debts

Sarah has three outstanding debts:

  • A car loan of $20,000 at 5.5% annual interest.
  • A personal loan of $10,000 at 9.0% annual interest.
  • A credit card balance of $5,000 at 18.0% annual interest.

Inputs:

  • Loan 1: Principal = $20,000, Rate = 5.5%
  • Loan 2: Principal = $10,000, Rate = 9.0%
  • Loan 3: Principal = $5,000, Rate = 18.0%

Calculation:

  • Total Principal = $20,000 + $10,000 + $5,000 = $35,000
  • Total Annual Interest = (20000 * 0.055) + (10000 * 0.090) + (5000 * 0.180) = $1,100 + $900 + $900 = $2,900
  • Weighted Average Interest Rate = $2,900 / $35,000 ≈ 0.08286 or 8.29%

Interpretation: Sarah's overall borrowing cost across these three debts is approximately 8.29% annually. This is lower than the simple average ( (5.5 + 9.0 + 18.0) / 3 ≈ 10.83% ) because the largest portion of her debt ($20,000) is at the lowest rate (5.5%). This highlights the importance of focusing on reducing high-interest, smaller balances first.

Example 2: Small Business Financing

A small business has the following financing:

  • A line of credit for $50,000 at 7.0% annual interest.
  • A term loan for $100,000 at 6.0% annual interest.
  • Equipment financing for $30,000 at 8.5% annual interest.

Inputs:

  • Loan 1: Principal = $50,000, Rate = 7.0%
  • Loan 2: Principal = $100,000, Rate = 6.0%
  • Loan 3: Principal = $30,000, Rate = 8.5%

Calculation:

  • Total Principal = $50,000 + $100,000 + $30,000 = $180,000
  • Total Annual Interest = (50000 * 0.070) + (100000 * 0.060) + (30000 * 0.085) = $3,500 + $6,000 + $2,550 = $12,050
  • Weighted Average Interest Rate = $12,050 / $180,000 ≈ 0.06694 or 6.69%

Interpretation: The business's blended annual interest cost is approximately 6.69%. The lower weighted average compared to the simple average ( (7.0 + 6.0 + 8.5) / 3 ≈ 7.17% ) is due to the largest portion of the financing ($100,000) being at the lowest rate (6.0%). Understanding this helps the business in strategic financial planning, such as prioritizing early repayment of the equipment financing due to its higher effective cost within the portfolio.

How to Use This Weighted Average Interest Rate Calculator

Our calculator is designed for simplicity and accuracy. Follow these steps to determine your weighted average interest rate:

  1. Input Loan Details: Enter the principal amount and the annual interest rate for each of your loans or debts into the respective fields. The calculator is pre-filled with sample data for three loans, but you can adjust these or imagine adding more conceptually.
  2. Check Input Validity: Ensure all values are positive numbers. Rates should be entered as percentages (e.g., 5.5 for 5.5%). The calculator includes inline validation to help catch errors.
  3. Calculate: Click the "Calculate" button. The calculator will instantly process your inputs.
  4. Review Results:
    • Primary Result: The most prominent display shows your Weighted Average Interest Rate.
    • Intermediate Values: You'll also see the Total Principal Amount, Total Annual Interest Paid, and the Simple Average Interest Rate for comparison.
    • Data Table: A summary table breaks down the contribution of each loan, including its weight and annual interest cost.
    • Chart: A visual representation shows the distribution of principal amounts across your loans.
  5. Interpret the Findings: Use the weighted average rate to understand your overall borrowing cost. Compare it to the simple average to see the impact of different loan sizes. High weighted averages might indicate a need to refinance or prioritize paying down high-interest debts.
  6. Reset or Copy: Use the "Reset" button to clear the fields and start over with default values. The "Copy Results" button allows you to easily transfer the key figures to a report or spreadsheet.

By regularly using this calculator, you can stay informed about your financial obligations and make better-informed decisions regarding debt management and financial strategy.

Key Factors That Affect Weighted Average Interest Rate Results

Several factors influence the calculated weighted average interest rate. Understanding these helps in interpreting the results and making strategic financial decisions:

  1. Principal Amounts (Weights): This is the most significant factor. Larger principal amounts have a greater influence on the weighted average. A loan with a substantial balance, even at a moderate rate, can significantly pull the average up or down. For instance, a $100,000 mortgage at 4% will have a much larger impact than a $2,000 credit card balance at 20%.
  2. Individual Interest Rates: The rates themselves are fundamental. Loans with higher interest rates will increase the weighted average more per dollar of principal than loans with lower rates. Conversely, large loans at low rates will decrease the weighted average.
  3. Number of Loans/Debts: While not directly in the formula, the more loans you have, the more complex the calculation becomes, and the more diversified your interest rate exposure. A portfolio with vastly different rates across many loans might have a weighted average that obscures critical individual debt costs.
  4. Loan Structure and Terms: While the calculator focuses on the current principal and rate, the remaining term of the loan affects the total interest paid over time. Shorter-term, high-interest loans might be prioritized for faster repayment to reduce their impact on long-term interest costs.
  5. Type of Debt: Different debt types often come with different typical interest rate ranges (e.g., mortgages vs. credit cards). Understanding the context of each rate is crucial. A high weighted average might be acceptable if it's primarily driven by essential, long-term, lower-rate debt like a mortgage.
  6. Refinancing and Consolidation Decisions: Actively managing your debts by refinancing high-interest loans or consolidating multiple debts can directly lower your weighted average interest rate. The calculator can be used to model the impact of such decisions before they are made.
  7. Fees and Associated Costs: While not directly part of the interest rate calculation, loan origination fees, annual fees, or prepayment penalties can increase the effective cost of borrowing. These should be considered alongside the weighted average interest rate for a holistic view.
  8. Economic Conditions (Inflation & Central Bank Rates): Broader economic factors influence the interest rates offered by lenders. Rising inflation or central bank rate hikes often lead to higher interest rates across the board, which will eventually increase the weighted average interest rate for new or variable-rate loans.

Frequently Asked Questions (FAQ)

Q1: How is the weighted average interest rate different from a simple average?

A: A simple average treats all loans equally, adding their rates and dividing by the number of loans. The weighted average assigns importance (weight) to each loan based on its principal amount, making larger loans have a greater impact on the final average rate.

Q2: Can this calculator handle more than three loans?

A: The calculator interface is set up for three loans for simplicity. To calculate for more loans, you would extend the formula manually or use a spreadsheet program like Excel, which is highly recommended for numerous entries. The underlying principle remains the same.

Q3: What's a "good" weighted average interest rate?

A: There's no universal "good" rate, as it depends heavily on the types of loans (mortgage vs. credit card), market conditions, and individual financial goals. Generally, a lower weighted average interest rate indicates a lower overall cost of borrowing, which is favorable.

Q4: Should I prioritize paying off the loan with the highest interest rate or the largest principal?

A: Financially, it's often recommended to prioritize paying off the loan with the highest interest rate first (the "debt avalanche" method). This strategy minimizes the total interest paid over time, thereby lowering your weighted average interest rate more effectively in the long run.

Q5: Does the weighted average interest rate account for loan fees?

A: The basic calculation focuses purely on principal and stated interest rates. It doesn't directly include fees (like origination fees, annual fees). To get a true "total cost of borrowing," you'd need to consider the Annual Percentage Rate (APR), which incorporates some fees, or perform a more complex analysis.

Q6: What if I have variable rate loans?

A: For variable rate loans, you should use the *current* interest rate for the calculation. Be aware that the weighted average will fluctuate as variable rates change. You might want to recalculate periodically or use the calculator to model potential rate increases.

Q7: How can I lower my weighted average interest rate?

A: You can lower it by: 1) Paying down larger principal balances faster, 2) Refinancing high-interest loans into lower-interest ones, 3) Consolidating multiple debts into a single loan with a lower average rate, and 4) Avoiding new high-interest debt.

Q8: Can I use this for investments too?

A: Yes, the concept is applicable. If you have multiple investments (like bonds) with different coupon rates and values, you can use the same formula to calculate the weighted average yield of your investment portfolio.

© 2023 Your Financial Website. All rights reserved.

var chartInstance = null; // Global variable to hold chart instance function validateInput(id, errorId, min, max) { var input = document.getElementById(id); var errorElement = document.getElementById(errorId); var value = parseFloat(input.value); var isValid = true; errorElement.textContent = "; // Clear previous error if (isNaN(value)) { errorElement.textContent = 'Please enter a number.'; isValid = false; } else if (value max) { errorElement.textContent = 'Value exceeds maximum limit.'; isValid = false; } input.style.borderColor = isValid ? '#ccc' : 'red'; return isValid; } function calculateWeightedAverage() { var loanAmounts = []; var interestRates = []; var annualInterests = []; var weights = []; var totalPrincipal = 0; var totalInterest = 0; var weightedRateSum = 0; var inputsValid = true; for (var i = 1; i 0) { weightedAverageRate = (weightedRateSum / totalPrincipal) * 100; // Convert back to percentage } var simpleAverageRate = 0; var validRatesCount = 0; for (var i = 0; i 0) { // Only consider loans with principal simpleAverageRate += interestRates[i]; validRatesCount++; } } if (validRatesCount > 0) { simpleAverageRate = (simpleAverageRate / validRatesCount) * 100; } document.getElementById('main-result').textContent = weightedAverageRate.toFixed(2) + '%'; document.getElementById('totalPrincipal').textContent = '$' + totalPrincipal.toFixed(2); document.getElementById('totalInterest').textContent = '$' + totalInterest.toFixed(2); document.getElementById('simpleAverageRate').textContent = simpleAverageRate.toFixed(2) + '%'; // Update table for (var i = 0; i 0) ? (loanAmounts[i] / totalPrincipal) * 100 : 0; weights.push(weight); document.getElementById('tableLoanAmount' + (i + 1)).textContent = '$' + loanAmounts[i].toFixed(2); document.getElementById('tableInterestRate' + (i + 1)).textContent = (interestRates[i] * 100).toFixed(2) + '%'; document.getElementById('tableAnnualInterest' + (i + 1)).textContent = '$' + annualInterests[i].toFixed(2); document.getElementById('tableWeight' + (i + 1)).textContent = weight.toFixed(2) + '%'; } document.getElementById('tableTotalPrincipal').textContent = '$' + totalPrincipal.toFixed(2); document.getElementById('tableTotalAnnualInterest').textContent = '$' + totalInterest.toFixed(2); updateChart(loanAmounts, 'Loan Principal Distribution'); } function resetCalculator() { document.getElementById('loanAmount1').value = '50000'; document.getElementById('interestRate1').value = '4.5'; document.getElementById('loanAmount2').value = '75000'; document.getElementById('interestRate2').value = '6.2'; document.getElementById('loanAmount3').value = '25000'; document.getElementById('interestRate3').value = '3.8'; // Clear errors document.getElementById('loanAmount1Error').textContent = "; document.getElementById('interestRate1Error').textContent = "; document.getElementById('loanAmount2Error').textContent = "; document.getElementById('interestRate2Error').textContent = "; document.getElementById('loanAmount3Error').textContent = "; document.getElementById('interestRate3Error').textContent = "; // Reset input borders document.getElementById('loanAmount1').style.borderColor = '#ccc'; document.getElementById('interestRate1').style.borderColor = '#ccc'; document.getElementById('loanAmount2').style.borderColor = '#ccc'; document.getElementById('interestRate2').style.borderColor = '#ccc'; document.getElementById('loanAmount3').style.borderColor = '#ccc'; document.getElementById('interestRate3').style.borderColor = '#ccc'; calculateWeightedAverage(); // Recalculate with default values } function copyResults() { var mainResult = document.getElementById('main-result').textContent; var totalPrincipal = document.getElementById('totalPrincipal').textContent; var totalInterest = document.getElementById('totalInterest').textContent; var simpleAverageRate = document.getElementById('simpleAverageRate').textContent; var tableLoan1Amount = document.getElementById('tableLoanAmount1').textContent; var tableLoan1Rate = document.getElementById('tableInterestRate1').textContent; var tableLoan1Interest = document.getElementById('tableAnnualInterest1').textContent; var tableLoan1Weight = document.getElementById('tableWeight1').textContent; var tableLoan2Amount = document.getElementById('tableLoanAmount2').textContent; var tableLoan2Rate = document.getElementById('tableInterestRate2').textContent; var tableLoan2Interest = document.getElementById('tableAnnualInterest2').textContent; var tableLoan2Weight = document.getElementById('tableWeight2').textContent; var tableLoan3Amount = document.getElementById('tableLoanAmount3').textContent; var tableLoan3Rate = document.getElementById('tableInterestRate3').textContent; var tableLoan3Interest = document.getElementById('tableAnnualInterest3').textContent; var tableLoan3Weight = document.getElementById('tableWeight3').textContent; var totalPrincipalText = document.getElementById('tableTotalPrincipal').textContent; var totalInterestText = document.getElementById('tableTotalAnnualInterest').textContent; var textToCopy = "Weighted Average Interest Rate Calculation Results:\n\n"; textToCopy += "Weighted Average Interest Rate: " + mainResult + "\n"; textToCopy += "Total Principal Amount: " + totalPrincipal + "\n"; textToCopy += "Total Annual Interest Paid: " + totalInterest + "\n"; textToCopy += "Simple Average Interest Rate: " + simpleAverageRate + "\n\n"; textToCopy += "Loan Details:\n"; textToCopy += "Loan 1 – Principal: " + tableLoan1Amount + ", Rate: " + tableLoan1Rate + ", Annual Interest: " + tableLoan1Interest + ", Weight: " + tableLoan1Weight + "\n"; textToCopy += "Loan 2 – Principal: " + tableLoan2Amount + ", Rate: " + tableLoan2Rate + ", Annual Interest: " + tableLoan2Interest + ", Weight: " + tableLoan2Weight + "\n"; textToCopy += "Loan 3 – Principal: " + tableLoan3Amount + ", Rate: " + tableLoan3Rate + ", Annual Interest: " + tableLoan3Interest + ", Weight: " + tableLoan3Weight + "\n\n"; textToCopy += "Totals – Principal: " + totalPrincipalText + ", Annual Interest: " + totalInterestText + "\n\n"; textToCopy += "Formula Used: Weighted Average Interest Rate = Sum(Principal * Rate) / Sum(Principal)"; navigator.clipboard.writeText(textToCopy).then(function() { alert('Results copied to clipboard!'); }, function(err) { console.error('Failed to copy: ', err); alert('Failed to copy results. Please copy manually.'); }); } function updateTableAndChart(loanAmounts, interestRates, annualInterests, weights, totalPrincipal, totalInterest) { // Update table – handles cases where calculation failed for (var i = 0; i a + b, 0) === 0) { if (chartInstance) { chartInstance.destroy(); chartInstance = null; } var ctx = document.getElementById('loanDistributionChart').getContext('2d'); ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // Clear canvas return; } updateChart(loanAmounts, 'Loan Principal Distribution'); } function updateChart(data, title) { var ctx = document.getElementById('loanDistributionChart').getContext('2d'); // Destroy previous chart instance if it exists if (chartInstance) { chartInstance.destroy(); } var labels = []; var datasets = [{ label: 'Principal Amount ($)', data: [], backgroundColor: [ 'rgba(0, 74, 153, 0.7)', // Primary color 'rgba(40, 167, 69, 0.7)', // Success color 'rgba(108, 117, 125, 0.7)' // Secondary color ], borderColor: [ 'rgba(0, 74, 153, 1)', 'rgba(40, 167, 69, 1)', 'rgba(108, 117, 125, 1)' ], borderWidth: 1 }]; for (var i = 0; i < data.length; i++) { labels.push('Loan ' + (i + 1)); datasets[0].data.push(data[i]); } chartInstance = new Chart(ctx, { type: 'pie', // Pie chart is suitable for distribution data: { labels: labels, datasets: datasets }, options: { responsive: true, maintainAspectRatio: true, plugins: { title: { display: true, text: title, font: { size: 18 }, color: 'var(–primary-color)' }, legend: { position: 'top', } } } }); } // Initial calculation on load window.onload = function() { calculateWeightedAverage(); // Ensure chart canvas is available and potentially clear it initially if no data var ctx = document.getElementById('loanDistributionChart').getContext('2d'); if (ctx) { ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); } };

Leave a Comment