Chartjs-ChartJS: Two Titles for positive and negative part of y axis

2👍

You can draw the y-axis scale labels directly on the canvas using the Plugin Core API. It offers a number of hooks that can be used to perform custom code. In your case, you could use the afterDraw hook as follows:

plugins: [{
  afterDraw: chart => {
    var ctx = chart.chart.ctx;
    ctx.save();
    var xAxis = chart.scales["x-axis-0"];
    var yAxis = chart.scales["y-axis-0"];
    ctx.fillStyle = "rgba(0, 0, 0, 0.8)";
    ctx.textAlign = "center";
    var fontSize = 12;
    ctx.font = fontSize + "px Arial";
    ctx.rotate(-Math.PI / 2);
    var yZero = yAxis.getPixelForValue(0);
    ctx.fillText("Dataset 1", yZero / -2, fontSize);
    ctx.fillText("Dataset 2", (yAxis.bottom + yZero) / -2, fontSize);
    ctx.restore();
  }
}],

You also need to define a value for layout.padding.left inside the chart options in order to avoid that your scale labels overlap the tick labels.

options: {
  layout: {
    padding: {
      left: 12
    }
  },

Please have a look at below runnable code snippet.

new Chart(document.getElementById("chart"), {
  type: "bar",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      var xAxis = chart.scales["x-axis-0"];
      var yAxis = chart.scales["y-axis-0"];
      ctx.fillStyle = "rgba(0, 0, 0, 0.8)";
      ctx.textAlign = "center";
      var fontSize = 12;
      ctx.font = fontSize + "px Arial";
      ctx.rotate(-Math.PI / 2);            
      var yZero = yAxis.getPixelForValue(0);
      ctx.fillText("Dataset 1", yZero / -2, fontSize);
      ctx.fillText("Dataset 2", (yAxis.bottom + yZero) / -2, fontSize);
      ctx.restore();
    }
  }],
  data: {
    labels: ["A", "B", "C"],
    datasets: [{
        label: "Dataset 1",
        data: [1, 2, 3],
        backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)"],
        borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)"],
        borderWidth: 1
      },
      {
        label: "Dataset 2",
        data: [-1, -2, -3],
        backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)"],
        borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)"],
        borderWidth: 1
      }
    ]
  },
  options: {
    layout: {
      padding: {
        left: 12
      }
    },
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        stacked: true,
      }],
      yAxes: [{
        stacked: true
      }]
    }
  }
});
canvas {
  max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="200"></canvas>

Leave a comment