Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chartjs scaleLabel position

Trying to get the Y axis scale labels to look like the image, to be position on top of the scale and not rotated.

scale options currently look like:

    scales: {
  yAxes: [{
    id: 'temp',
    scaleLabel: {
      display: true,
      labelString: '°C'
    },
    type: 'linear',
    position: 'left'
  }, {
    id: 'ppm',
    scaleLabel: {
      display: true,
      labelString: 'ppm',
    },
    type: 'linear',
    position: 'left',
    ticks: {
      stepSize: 500
    }
  }, {
    id: '%',
    scaleLabel: {
      display: true,
      labelString: '%',
    },
    type: 'linear',
    position: 'right',
    ticks: {
      max: 100,
      min: 0
    }
  }]
}

https://jsfiddle.net/3a7qvtwz/2/

like image 982
Jack Mason Avatar asked Nov 15 '17 16:11

Jack Mason


1 Answers

You can use the Plugin Core API that offers a range of hooks that may be used for performing custom code. To draw the scale labels on top of the different yAxes in your code sample, the afterDraw hook could be defined as follows. It uses CanvasRenderingContext2D.fillText() to draw text directly on the canvas.

plugins:[{
  afterDraw: chart => {
    var ctx = chart.chart.ctx;
    ctx.save();
    ctx.font = "bold 14px Arial";
    ctx.fillStyle = "gray";
    var y = 50;

    ctx.textAlign = 'left';        
    ctx.fillText('CO2', 5, y);
    ctx.fillText('°C', 46, y);

    ctx.textAlign = 'right';
    ctx.fillText('%', chart.chart.width - 10, y);
    ctx.restore();
  }
}],

Please have a look at your amended JSFiddle

like image 196
uminder Avatar answered Oct 23 '22 20:10

uminder