Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js - How to Add Text in the Middle of the Chart?

Tags:

chart.js

I'm using Chart.js to create this line chart:

enter image description here

But I need to label the zones, something like this:

enter image description here

Any Ideas?

like image 272
Thomas Fifield Avatar asked Jun 02 '15 18:06

Thomas Fifield


People also ask

What do you mean by doughnut chart?

Doughnut charts show each cell's data as a slice of a doughnut. The chart may contain one or more doughnuts, arranged one inside the other. Doughnut charts let you show the relationship of parts of several sets of data to the whole. Each doughnut shows a series of data.


1 Answers

You extend the chart which you used and then write the labels using the helper methods

HTML

<canvas id="myChart" width="500" height="400"></canvas>

In the below JS, note that the parameter to calculateY is the y value, while for calculateX, it is label index

Chart.types.Line.extend({
  name: "LineAlt",
  draw: function(){
    Chart.types.Line.prototype.draw.apply(this, arguments);

    this.chart.ctx.textAlign = "center"
    // y value and x index
    this.chart.ctx.fillText("ZONE1", this.scale.calculateX(3.5), this.scale.calculateY(20.75))
    this.chart.ctx.fillText("ZONE2", this.scale.calculateX(11.5), this.scale.calculateY(13))
    this.chart.ctx.fillText("ZONE3", this.scale.calculateX(2), this.scale.calculateY(9.75))
    this.chart.ctx.fillText("ZONE4", this.scale.calculateX(14.5), this.scale.calculateY(22.75))
  }
});

var data = {
  labels: [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
  datasets: [{
    data: []
  }]
};

var ctx = document.getElementById("myChart").getContext("2d");
var myBarChart = new Chart(ctx).LineAlt(data, {
  scaleOverride: true,
  scaleSteps: 16,
  scaleStepWidth: 1,
  scaleStartValue: 8,
  animation: false
});

Fiddle - https://jsfiddle.net/bpfvvxpn/

Not sure how you created the line chart, so didn't add it to the fiddle

like image 159
potatopeelings Avatar answered Sep 24 '22 12:09

potatopeelings