Create Visual Correlation Matrices Using Canvas – draw-correlation-matrix.js

Category: Chart & Graph , Javascript | November 14, 2024
Authorvargalaszlo87
Last UpdateNovember 14, 2024
LicenseMIT
Tags
Views61 views
Create Visual Correlation Matrices Using Canvas – draw-correlation-matrix.js

draw-correlation-matrix.js is a lightweight JavaScript library that lets you render correlation matrices using the HTML5 canvas element.

The resulting visualization displays correlations as colored circles within a grid, with red indicating negative correlation and blue representing positive correlation. The size of the circle reflects the strength of the correlation.

How to use it:

1. Download draw-correlation-matrix.js and include it on your webpage.

<script src="draw-correlation-matrix.js"></script>

2. Add a <canvas> element to your page where the matrix will be drawn:

<canvas id="matrixCanvas"></canvas>

3. Define the correlation matrix (a 2D array) and the labels for the axes (rows and columns).

const corrMatrix = [
  [1.00, 0.25, -0.62, 0.38, -0.11, 0.75],
  [0.25, 1.00, 0.08, -0.21, 0.59, -0.34],
  [-0.62, 0.08, 1.00, -0.55, 0.26, -0.81],
  [0.38, -0.21, -0.55, 1.00, -0.47, 0.19],
  [-0.11, 0.59, 0.26, -0.47, 1.00, -0.07],
  [0.75, -0.34, -0.81, 0.19, -0.07, 1.00]
];
const labels = ["Apples", "Bananas", "Cherries", "Dates", "Elderberries", "Figs"];

4. Call the drawCorrelationMatrix.chart() function and specify the canvas ID, matrix size, labels, and the data:

drawCorrelationMatrix.chart("matrixCanvas", 6, labels, corrMatrix);

5. Modify the default settings (cell size, font, margins) directly within the draw-correlation-matrix.js file.

// cell & margin
cellSize: 60,
labelMargin: 120,
// font
fontSize: 18,
fontFamily: "Arial",

You Might Be Interested In:


Leave a Reply