Chartjs-Place the labels on the bar and line chart separately

0👍

for the bars, the labels seem to appear above by default.
otherwise, you can do the same as the line options, as follows.

for the line, you can use datalabels option align
add the option(s) to the lineChart constant, as follows…
here, I’ve added offset to add a little distance from the point.

const lineChart = {
  type: "line",
  label: "Line Dataset",
  data: l2,
  datalabels: {       <-- add options here
    align: 'bottom',
    anchor: 'end',
    offset: 8
  },
  yAxisID: "rel",
  order: 1,
  tension: 0.4
};

see following working snippet…

const ctx = document.getElementById("barCanvas");
/* ------------------------ DATA ----------------------------------- */
let l1 = [];
let l2 = [];
for (let i = 0; i < 10; i++) {
  l1.push(Math.floor(Math.random() * 100) + 1);
  l2.push(Math.floor(Math.random() * 10) + 1);
}
const date = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

/* ------------------------ BAR --------------------- */
const barChart = {
  type: "bar",
  yAxisID: "y",
  label: "Weekly Sales",
  data: l1,
  backgroundColor: ["rgba(255, 26, 104, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(255, 206, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(0, 0, 0, 0.2)"],
  borderColor: ["rgba(255, 26, 104, 1)", "rgba(54, 162, 235, 1)", "rgba(255, 206, 86, 1)", "rgba(75, 192, 192, 1)", "rgba(153, 102, 255, 1)", "rgba(255, 159, 64, 1)", "rgba(0, 0, 0, 1)"],
  borderWidth: 1,
  order: 2
};

/* ------------------------ LINE --------------------- */
const lineChart = {
  type: "line",
  label: "Line Dataset",
  data: l2,
  datalabels: {
    align: 'bottom',
    anchor: 'end',
    offset: 8
  },
  yAxisID: "rel",
  order: 1,
  tension: 0.4
};

/* ------------------------ SCALE --------------------- */
const scalesChart = {
  y: {
    //anchor: 'end',
    //align: 'top',
    type: "linear",
    position: "left",
    beginAtZero: true
  },
  rel: {
    type: "linear",
    position: "right",
    beginAtZero: true,
    suggestedMin: 0,
    suggestedMax: Math.max(...l2) + 3,
    grid: {
      display: false
    }
  }
};

const mixedChart = new Chart(ctx, {
  data: {
    datasets: [barChart, lineChart],
    labels: date
  },
  options: {
    scales: scalesChart,
    plugins: {
      datalabels: {
        //y: {
        anchor: 'end',
        align: 'top',
        //}
      }

    }
  },
  plugins: [ChartDataLabels]
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Graph</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>
</head>

<body>
  <h1>Graphique</h1>
  <div class="chart-container">
    <canvas id="barCanvas" aria-label="chart" role="img"></canvas>
  </div>
</body>

</html>

Leave a comment