Basic Heatmap in Chart.js (JavaScript)

The same plot in 14 other libraries — JavaScript: D3.js, Apache ECharts, Highcharts, MUI X Charts; Python: Altair, Bokeh, lets-plot, Matplotlib, Plotly, plotnine, Pygal, Seaborn; R: ggplot2; Julia: Makie.jl. Compare all 15 side by side: Basic Heatmap in Python, R, Julia and JavaScript.

A heatmap displaying values in a matrix format using color intensity. Each cell's color represents the magnitude of the value, making it easy to identify patterns, clusters, and outliers in two-dimensional data. Essential for visualizing correlations, frequencies, and relationships between variables.

Basic Heatmap rendered with Chart.js

Renders

JavaScript source (Chart.js)

// anyplot.ai
// heatmap-basic: Basic Heatmap
// Library: chartjs 4.6.1 | JavaScript 22.23.5
// Quality: 82/100 | Updated: 2026-12-05
//# anyplot-orientation: square

const t = window.ANYPLOT_TOKENS;

// Data — Pearson correlations between 10 macroeconomic indicators.
// Diverging polarity (−1..+1) → Imprint diverging ramp (fields: cells fill the plot).
const labels = [
  "GDP",
  "Unemploy.",
  "Inflation",
  "Interest",
  "Stocks",
  "Housing",
  "Cons. Conf.",
  "Exports",
  "Imports",
  "Wages",
];
const N = labels.length;

const matrix = [
  [ 1.00, -0.62,  0.18,  0.31,  0.74,  0.66,  0.71,  0.58,  0.45, -0.14],
  [-0.62,  1.00, -0.22, -0.48, -0.55, -0.59, -0.81, -0.41, -0.35, -0.07],
  [ 0.18, -0.22,  1.00,  0.69, -0.07, -0.31, -0.42, -0.05,  0.21,  0.46],
  [ 0.31, -0.48,  0.69,  1.00,  0.12, -0.15, -0.33,  0.07,  0.18,  0.39],
  [ 0.74, -0.55, -0.07,  0.12,  1.00,  0.58,  0.79,  0.61,  0.40, -0.21],
  [ 0.66, -0.59, -0.31, -0.15,  0.58,  1.00,  0.66,  0.42,  0.28, -0.18],
  [ 0.71, -0.81, -0.42, -0.33,  0.79,  0.66,  1.00,  0.48,  0.37,  0.12],
  [ 0.58, -0.41, -0.05,  0.07,  0.61,  0.42,  0.48,  1.00,  0.73,  0.24],
  [ 0.45, -0.35,  0.21,  0.18,  0.40,  0.28,  0.37,  0.73,  1.00,  0.31],
  [-0.14, -0.07,  0.46,  0.39, -0.21, -0.18,  0.12,  0.24,  0.31,  1.00],
];

// Plot

// Color at v (0..1) along [position, hex] stops, blended linearly in sRGB.
const rampAt = (stops, v) => {
  const x = Math.min(1, Math.max(0, v));
  const i = Math.max(1, stops.findIndex(([p]) => p >= x));
  const [[p0, c0], [p1, c1]] = [stops[i - 1], stops[i]];
  const f = (x - p0) / (p1 - p0);
  const ch = (c, k) => parseInt(c.slice(1 + 2 * k, 3 + 2 * k), 16);
  return "#" + [0, 1, 2].map((k) => Math.round(ch(c0, k) + (ch(c1, k) - ch(c0, k)) * f).toString(16).padStart(2, "0")).join("");
};
const cellColor = (v) => rampAt(t.divFields, (v + 1) / 2);

// WCAG relative luminance of a "#rrggbb" color.
const luminance = (hex) => {
  const lin = (k) => {
    const c = parseInt(hex.slice(1 + 2 * k, 3 + 2 * k), 16) / 255;
    return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
  };
  return 0.2126 * lin(0) + 0.7152 * lin(1) + 0.0722 * lin(2);
};
const contrast = (a, b) => {
  const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
  return (hi + 0.05) / (lo + 0.05);
};
// In-cell text: whichever of the theme's ink and page color contrasts more with the fill.
const textOn = (fill) => (contrast(fill, t.ink) >= contrast(fill, t.pageBg) ? t.ink : t.pageBg);

const FONT_STACK =
  '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif';

// Each column of the matrix is one stacked-bar dataset; every row is one bar
// of unit length, so the bars tile into a grid and each segment is a cell.
const datasets = labels.map((name, j) => ({
  label: name,
  data: matrix.map(() => 1),
  backgroundColor: matrix.map((row) => cellColor(row[j])),
  borderColor: t.grid,
  borderWidth: 1,
  borderSkipped: false,
  barPercentage: 1,
  categoryPercentage: 1,
}));

// Draws the value inside every cell (text only) and the colorbar in the
// right-hand padding.
const annotations = {
  id: "cell-values-colorbar",
  afterDatasetsDraw(chart) {
    const { ctx, chartArea, width } = chart;
    const { right, top, bottom } = chartArea;

    ctx.save();
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.font = `500 16px ${FONT_STACK}`;
    chart.data.datasets.forEach((_, j) => {
      chart.getDatasetMeta(j).data.forEach((bar, i) => {
        const v = matrix[i][j];
        ctx.fillStyle = textOn(cellColor(v));
        ctx.fillText(v.toFixed(2), bar.x - bar.width / 2, bar.y);
      });
    });
    ctx.restore();

    const cbLeft = right + 32;
    const cbW = 24;
    const cbH = bottom - top;
    const grad = ctx.createLinearGradient(0, top, 0, bottom);
    t.divFields.forEach(([p, hex]) => grad.addColorStop(1 - p, hex));
    ctx.fillStyle = grad;
    ctx.fillRect(cbLeft, top, cbW, cbH);

    ctx.save();
    ctx.font = `400 15px ${FONT_STACK}`;
    ctx.fillStyle = t.inkSoft;
    ctx.strokeStyle = t.inkSoft;
    ctx.lineWidth = 1;
    ctx.textAlign = "left";
    ctx.textBaseline = "middle";
    for (const v of [1, 0.5, 0, -0.5, -1]) {
      const y = top + (1 - (v + 1) / 2) * cbH;
      ctx.beginPath();
      ctx.moveTo(cbLeft + cbW, y);
      ctx.lineTo(cbLeft + cbW + 5, y);
      ctx.stroke();
      ctx.fillText(v.toFixed(1), cbLeft + cbW + 11, y);
    }
    ctx.restore();

    // Colorbar title, rotated to read bottom-to-top.
    ctx.save();
    ctx.fillStyle = t.ink;
    ctx.font = `500 17px ${FONT_STACK}`;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.translate(width - 16, (top + bottom) / 2);
    ctx.rotate(-Math.PI / 2);
    ctx.fillText("Pearson correlation (r)", 0, 0);
    ctx.restore();
  },
};

const canvas = document.createElement("canvas");
document.getElementById("container").appendChild(canvas);

new Chart(canvas, {
  type: "bar",
  data: { labels, datasets },
  options: {
    indexAxis: "y",
    responsive: true,
    maintainAspectRatio: false,
    animation: false,
    layout: { padding: { top: 4, right: 170, bottom: 4, left: 4 } },
    plugins: {
      title: {
        display: true,
        text: "Macro Indicator Correlations · heatmap-basic · javascript · chartjs · anyplot.ai",
        color: t.ink,
        font: { size: 20, weight: "500" },
        padding: { top: 4, bottom: 18 },
      },
      legend: { display: false },
      tooltip: { enabled: false },
    },
    scales: {
      x: {
        stacked: true,
        min: 0,
        max: N,
        position: "top",
        afterBuildTicks: (axis) => {
          axis.ticks = Array.from({ length: N }, (_, j) => ({ value: j + 0.5 }));
        },
        ticks: {
          color: t.inkSoft,
          font: { size: 16 },
          autoSkip: false,
          callback: (v) => labels[Math.floor(v)],
          maxRotation: 35,
          minRotation: 35,
        },
        grid: { display: false },
        border: { display: false },
      },
      y: {
        stacked: true,
        ticks: { color: t.inkSoft, font: { size: 16 }, autoSkip: false },
        grid: { display: false },
        border: { display: false },
      },
    },
  },
  plugins: [annotations],
});

Retrieve this implementation

Runnable source as JSON, for any HTTP client: https://api.anyplot.ai/specs/heatmap-basic/chartjs/code. Any spec id and library id listed in llms-full.txt fit the same URL shape; every URL below is complete and callable.

{
  "spec_id": "heatmap-basic",
  "language": "javascript",
  "library": "chartjs",
  "page": "https://anyplot.ai/heatmap-basic/javascript/chartjs",
  "hub": "https://anyplot.ai/heatmap-basic",
  "code_json": "https://api.anyplot.ai/specs/heatmap-basic/chartjs/code",
  "spec_json": "https://api.anyplot.ai/specs/heatmap-basic",
  "render_light_png": "https://storage.googleapis.com/anyplot-images/plots/heatmap-basic/javascript/chartjs/plot-light.png",
  "render_dark_png": "https://storage.googleapis.com/anyplot-images/plots/heatmap-basic/javascript/chartjs/plot-dark.png",
  "interactive_light_html": "https://storage.googleapis.com/anyplot-images/plots/heatmap-basic/javascript/chartjs/plot-light.html",
  "interactive_dark_html": "https://storage.googleapis.com/anyplot-images/plots/heatmap-basic/javascript/chartjs/plot-dark.html",
  "quality_score": 82.0,
  "license": "MIT",
  "guide": "https://anyplot.ai/llms.txt"
}

Part of Basic Heatmap on anyplot.ai.

Other implementations