Chartjs-Chart.js boxplot: adding additional reference value?

0👍

If I understand it correctly you can add those custom propertys in the dataset. After this you can use the datalabels plugin to visualize them:

Chart.register(ChartDataLabels)

function randomValues(count, min, max) {
  const delta = max - min;
  return Array.from({
    length: count
  }).map(() => Math.random() * delta + min);
}

const boxplotData = {
  // define label tree
  labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
  datasets: [{
    x: 8,
    y: 16,
    z: 2,
    label: 'Dataset 1',
    backgroundColor: 'rgba(255,0,0,0.5)',
    borderColor: 'red',
    borderWidth: 1,
    outlierColor: '#999999',
    padding: 10,
    itemRadius: 0,
    data: [
      randomValues(100, 0, 100),
      randomValues(100, 0, 20),
      randomValues(100, 20, 70),
      randomValues(100, 60, 100),
      randomValues(40, 50, 100),
      randomValues(100, 60, 120),
      randomValues(100, 80, 100)
    ]
  }, {
    x: 5,
    y: 6,
    z: 20,
    label: 'Dataset 2',
    backgroundColor: 'rgba(0,0,255,0.5)',
    borderColor: 'blue',
    borderWidth: 1,
    outlierColor: '#999999',
    padding: 10,
    itemRadius: 0,
    data: [
      randomValues(100, 60, 100),
      randomValues(100, 0, 100),
      randomValues(100, 0, 20),
      randomValues(100, 20, 70),
      randomValues(40, 60, 120),
      randomValues(100, 20, 100),
      randomValues(100, 80, 100)
    ]
  }]
};
window.onload = () => {
  const ctx = document.getElementById("canvas").getContext("2d");
  window.myBar = new Chart(ctx, {
    type: 'boxplot',
    data: boxplotData,
    options: {
      scales: {
        y: {
          grace: '5%'
        }
      },
      responsive: true,
      plugins: {
        datalabels: {
          formatter: (val, ctx) => (`${ctx.dataset.x} ${ctx.dataset.y} ${ctx.dataset.z}`),
          align: 'end',
          offset: (ctx) => {
            const center = ctx.chart.scales.y.getPixelForValue(ctx.chart.getDatasetMeta(ctx.datasetIndex)._parsed[ctx.dataIndex].mean);
            const max = ctx.chart.scales.y.getPixelForValue(ctx.chart.getDatasetMeta(ctx.datasetIndex)._parsed[ctx.dataIndex].max);
            return center - max;
          }
        }
      }
    }
  });

};
<script src="https://unpkg.com/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.js"></script>
<script src="https://unpkg.com/@sgratzl/chartjs-chart-boxplot@3.6.0/build/index.umd.min.js"></script>
<div id="container">
  <canvas id="canvas"></canvas>
</div>

codepen

Leave a comment