Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ChartJS rotate label value vertical

I'm using ChartJS to create a bar graph at this JSfiddle.

It is currently showing the value in horizontal as the result shows in the image below.

enter image description here

I'm trying to rotate this value by 90 degree so it displays as

enter image description here

Is there a way to do this via ChartJS options? I tried to play around with HTML5 's ctx.transform() and ctx.rotate() below but no luck so far.

    this.datasets.forEach(function (dataset) {
            dataset.bars.forEach(function (bar) {
                ctx.fillText(bar.value, bar.x, bar.y + 30);
                ctx.save();
                ctx.rotate(45 * Math.PI / 180);
            });
like image 720
Fylix Avatar asked Aug 05 '26 02:08

Fylix


1 Answers

You can use the translate and rotate properties to rotate the text:

var chartData = {
  labels: ["January", "February", "March", "April", "May", "June"],
  datasets: [{
    fillColor: "#79D1CF",
    strokeColor: "#79D1CF",
    data: [9045645, 4045645, 6045645, 8045645, 5045645, 6045645]
  }]
};


var ctx = document.getElementById("myChart2").getContext("2d");
var myBar = new Chart(ctx).Bar(chartData, {
  showTooltips: false,
  onAnimationComplete: function() {

    var ctx = this.chart.ctx;
    ctx.font = this.scale.font;
    ctx.fillStyle = this.scale.textColor
    ctx.textAlign = "center";
    ctx.textBaseline = "bottom";

    const lineHeigt = ctx.measureText('M').width;

    this.datasets.forEach(function(dataset) {
      dataset.bars.forEach(function(bar) {
        ctx.save();
        ctx.translate(bar.x + (lineHeigt / 3 * 2), bar.y + 30)
        ctx.rotate(-Math.PI / 2);
        ctx.fillText(bar.value, 0, 0);
        ctx.restore();
      });
    })
  }
});
<script src="https://rawgit.com/nnnick/Chart.js/v1.0.2/Chart.min.js"></script>

<canvas id="myChart2" height="300" width="500"></canvas>
like image 156
LeeLenalee Avatar answered Aug 06 '26 15:08

LeeLenalee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!