Chartjs-Split legend in chart js

1👍

You could create your own HTML Legend and apply a CSS grid layout. See the HTML legend demo.

const getOrCreateLegendList = (chart, id) => {
  const legendContainer = document.getElementById(id);
  let listContainer = legendContainer.querySelector('ul');

  if (!listContainer) {
    listContainer = document.createElement('ul');
    listContainer.style.display = 'flex';
    listContainer.style.flexDirection = 'row';
    listContainer.style.margin = 0;
    listContainer.style.padding = 0;

    legendContainer.appendChild(listContainer);
  }

  return listContainer;
};

const createLegendItem = (item, chart, legend) => {
  const li = document.createElement('li');
  li.style.alignItems = 'center';
  li.style.cursor = 'pointer';
  li.style.display = 'flex';
  li.style.flexDirection = 'row';
  li.style.marginLeft = '10px';

  li.onclick = () => {
    const { type } = chart.config;
    if (type === 'pie' || type === 'doughnut') {
      // Pie and doughnut charts only have a single dataset and visibility is per item
      chart.toggleDataVisibility(item.index);
    } else {
      chart.setDatasetVisibility(item.datasetIndex, !chart.isDatasetVisible(item.datasetIndex));
    }
    chart.update();
  };

  // Color box
  const boxSpan = document.createElement('span');
  boxSpan.style.background = item.fillStyle;
  boxSpan.style.borderColor = item.strokeStyle;
  boxSpan.style.borderWidth = item.lineWidth + 'px';
  boxSpan.style.display = 'inline-block';
  boxSpan.style.height = '20px';
  boxSpan.style.marginRight = '10px';
  boxSpan.style.width = '20px';

  // Text
  const textContainer = document.createElement('p');
  textContainer.style.color = item.fontColor;
  textContainer.style.margin = 0;
  textContainer.style.padding = 0;
  textContainer.style.textDecoration = item.hidden ? 'line-through' : '';

  const text = document.createTextNode(item.text);
  textContainer.appendChild(text);

  li.appendChild(boxSpan);
  li.appendChild(textContainer);
  legend.appendChild(li);
};

const htmlLegendPlugin = {
  id: 'htmlLegend',
  afterUpdate(chart, args, options) {
    const ul = getOrCreateLegendList(chart, options.containerID);

    // Remove old legend items
    while (ul.firstChild) ul.firstChild.remove();

    // Reuse the built-in legendItems generator
    chart.options.plugins.legend.labels.generateLabels(chart)
      .forEach(item => createLegendItem(item, chart, ul));
  }
};

const seriesDefaults = {
  fill: true,
  borderWidth: 1,
};

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      ...seriesDefaults,
      label: 'Left F/R Ratio',
      data: [12, 19, 3, 5, 2, 3],
      borderColor: 'rgba(192, 192, 255, 1)',
      backgroundColor: 'rgba(192 ,192, 255, 0.5)'
    }, {
      ...seriesDefaults,
      label: 'Right F/R Ratio',
      data: [11, 5, 8, 3, 7, 5],
      borderColor: 'rgba(64, 64, 255, 1)',
      backgroundColor: 'rgba(64 ,64, 255, 0.5)'
    }, {
      ...seriesDefaults,
      label: 'Left Peak Pressure',
      data: [19, 3, 5, 2, 3, 12],
      borderColor: 'rgba(255, 192, 192, 1)',
      backgroundColor: 'rgba(255, 192, 192, 0.5)'
    }, {
      ...seriesDefaults,
      label: 'Right Peak Pressure',
      data: [7, 11, 5, 8, 3, 7],
      borderColor: 'rgba(255, 64, 64, 1)',
      backgroundColor: 'rgba(255, 64 ,64, 0.5)'
    }]
  },
  options: {
    plugins: {
      htmlLegend: {
        containerID: 'legend-container'
      },
      legend: {
        display: false
      }
    }
  },
  plugins: [htmlLegendPlugin]
}

const ctx = document.getElementById('chart').getContext('2d');

new Chart(ctx, options);
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.chart-wrapper {
  display: flex;
  flex-direction: column;
}

.chart {
  display: flex;
  flex: 1;
}

#legend-container {
  display: flex;
  justify-content: center;
  padding: 0.5em;
}

#legend-container ul {
  display: grid !important;
  grid-template-columns: repeat(2, 1fr);
  grid-row-gap: 0.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<div class="chart-wrapper">
  <canvas id="chart"></canvas>
  <div id="legend-container"></div>
</div>

Leave a comment