[Chartjs]-Draw points and lines inside a bar in bar chart

1👍

You can draw the lines as floating bars where individual bars are specified with the syntax [min, max], same as you already do for your your other bars. Given an array of number values, the "line" data can be produced with Array.map() as follows.

data: [110, 150, 140, 100, 120].map(v => [v - 1, v + 1])

Then you need to define individual stacked xAxes for the "bar" and the "line" datasets. In order to have the original "line" values displayed in the tooltips, a toolips.callback.label function is also needed.

The points can be defined in an additional dataset of type 'scatter'.

Please have a look at below runnable code snippet.

new Chart("chart", {
  type: "bar",
  data: {
    labels: ["4", "3", "2", "1", "0"],
    datasets: [{
        label: "Bars",
        backgroundColor: "rgba(0, 255, 0, 0.2)",
        data: [[20, 100], [50, 180], [60, 120], [10, 130], [70, 140]],
        xAxisID: "x-axis-actual",
        order: 1
      },
      {
        label: "Lines",
        backgroundColor: "rgb(0, 0, 0)",
        data: [90, 150, 110, 90, 120].map(v => [v - 1, v + 1]),
        xAxisID: "x-axis-target",
        order: 2        
      },
      {
        label: "Points",
        backgroundColor: "rgb(255, 255, 255)",
        borderColor: "rgb(0, 0, 0)",
        data: [80, 110, 90, 100, 120],
        type: "scatter"        
      }
    ]
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      callbacks: {
        label: (tooltipItem, data) => {
          const dataset = data.datasets[tooltipItem.datasetIndex]; 
          const v = dataset.data[tooltipItem.index];
          return dataset.label + ': ' + (tooltipItem.datasetIndex == 1 ? (v[1] + v[0]) / 2 : tooltipItem.value);
        }
      }
    },
    scales: {
      xAxes: [{
          id: "x-axis-target",
          stacked: true
        },
        {
          display: false,
          offset: true,
          stacked: true,
          id: "x-axis-actual",
          gridLines: {
            offsetGridLines: true
          }
        }
      ],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="120"></canvas>

Leave a comment