Skip to content

Heatmap

Категории по обеим осям, значение colorField задаёт цвет ячейки по непрерывной шкале. Справа автоматически появляется градиентная легенда.

По умолчанию оси heatmap рисуются без линий, тиков и сетки — остаются только подписи категорий (вернуть можно через axes: [{ ..., line: { enabled: true } }]).

ts
import { getData } from './data';
import type { ChartOptions } from 'grafit-charts';

export function createOptions(): ChartOptions {
  return {
    data: getData(),
    title: { text: 'Load by hour' },
    series: [
      {
        type: 'heatmap',
        xField: 'day',
        yField: 'hour',
        colorField: 'load',
        colorName: 'Load',
        colorRange: ['#e8f0fe', '#1d4fd7'],
      },
    ],
    legend: { enabled: false },
  };
}
ts
export function getData() {
  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  const hours = ['00', '04', '08', '12', '16', '20'];
  const data: Array<{ day: string; hour: string; load: number }> = [];
  days.forEach((day, d) => {
    hours.forEach((hour, h) => {
      const base = h === 2 || h === 3 ? 60 : h === 4 ? 45 : 15;
      const weekend = d >= 5 ? 0.5 : 1;
      data.push({ day, hour, load: Math.round(base * weekend + ((d * 7 + h * 3) % 13)) });
    });
  });
  return data;
}

Расположение цветовой шкалы

gradientLegend управляет позицией, отступом и толщиной шкалы (в сборке через grafit-charts/core шкала — отдельный модуль: register(gradientLegendModule)):

ts
import { getData } from './data';
import type { ChartOptions } from 'grafit-charts';

export function createOptions(): ChartOptions {
  return {
    data: getData(),
    title: { text: 'Scale at the bottom with spacing' },
    series: [{ type: 'heatmap', xField: 'week', yField: 'day', colorField: 'deploys', colorName: 'Deploys' }],
    gradientLegend: { position: 'bottom', spacing: 14, thickness: 10 },
    legend: { enabled: false },
  };
}
ts
export function getData() {
  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
  const weeks = ['W1', 'W2', 'W3', 'W4'];
  const data: Array<{ week: string; day: string; deploys: number }> = [];
  weeks.forEach((week, w) => {
    days.forEach((day, d) => {
      data.push({ week, day, deploys: ((w * 5 + d * 3) % 11) + (d === 2 ? 6 : 1) });
    });
  });
  return data;
}
ОпцияТипПо умолчаниюОписание
gradientLegend.enabledbooleantrueпоказывать шкалу
gradientLegend.position'right' | 'bottom''right'сторона размещения
gradientLegend.spacingPixels10отступ от области построения
gradientLegend.thicknessPixels12толщина полосы

Подписи значений

label: { enabled: true } выводит значение в каждой ячейке; цвет текста подбирается автоматически по светимости фона. Тултип здесь привязан к центру ячейки (tooltip.position.anchorTo: 'center', по умолчанию — верхний край):

ts
import { getData } from './data';
import type { ChartOptions } from 'grafit-charts';

export function createOptions(): ChartOptions {
  return {
    data: getData(),
    title: { text: 'Value labels' },
    series: [
      {
        type: 'heatmap',
        xField: 'week',
        yField: 'day',
        colorField: 'deploys',
        colorName: 'Deploys',
        // text color is chosen automatically based on cell luminance
        label: { enabled: true },
      },
    ],
    // tooltip at the cell center
    tooltip: { position: { anchorTo: 'center' } },
    legend: { enabled: false },
  };
}
ts
export function getData() {
  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
  const weeks = ['W1', 'W2', 'W3', 'W4'];
  const data: Array<{ week: string; day: string; deploys: number }> = [];
  weeks.forEach((week, w) => {
    days.forEach((day, d) => {
      data.push({ week, day, deploys: ((w * 5 + d * 3) % 11) + (d === 2 ? 6 : 1) });
    });
  });
  return data;
}

Кастомные подписи

formatter, шрифт, цвет и размещение (placement: 'top') настраиваются; шкалу можно отключить:

ts
import { getData } from './data';
import type { ChartOptions } from 'grafit-charts';

export function createOptions(): ChartOptions {
  return {
    data: getData(),
    title: { text: 'Custom labels' },
    subtitle: { text: 'formatter, font and color; scale disabled' },
    series: [
      {
        type: 'heatmap',
        xField: 'week',
        yField: 'day',
        colorField: 'deploys',
        colorRange: ['#fef3e2', '#e8590c'],
        itemPadding: 4,
        cornerRadius: 8,
        label: {
          enabled: true,
          placement: 'top-left',
          formatter: ({ value }) => `${value}×`,
          fontSize: 13,
          fontWeight: 'bold',
        },
      },
    ],
    gradientLegend: { enabled: false },
    legend: { enabled: false },
  };
}
ts
export function getData() {
  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
  const weeks = ['W1', 'W2', 'W3', 'W4'];
  const data: Array<{ week: string; day: string; deploys: number }> = [];
  weeks.forEach((week, w) => {
    days.forEach((day, d) => {
      data.push({ week, day, deploys: ((w * 5 + d * 3) % 11) + (d === 2 ? 6 : 1) });
    });
  });
  return data;
}
ОпцияТипПо умолчаниюОписание
xFieldstringкатегории по осям
yFieldstringкатегории по осям
colorFieldstringчисловое значение → цвет
colorRangeColorValue[]сине-голубаястопы шкалы (2+)
itemPaddingPixels1зазор между ячейками
cornerRadiusPixels2скругление ячеек
colorNamestringимя colorFieldподпись значения в тултипе
label.enabledbooleanfalseпоказать подписи значений
label.placementcenter, края и углы (9 позиций)'center'позиция подписи
label.formatter({ value, datum }) => stringзначениесодержимое подписи
label.fontSizePixels11размер шрифта подписи
label.fontWeightstring | numbernormalнасыщенность
label.fontFamilystringшрифт темыгарнитура
label.colorColorValueforeground; внутри — автоконтрастцвет текста

Опции

Общие опции всех серий (name, showInLegend, tooltip.renderer, …) — в разделе Общие опции серий.