Chart.js 2 - How will I vertically insert the dataset values inside the bar graph?

882 views Asked by At

Current Bar Graph

I want to vertically insert the dataset values to their corresponding bar graph. What should I do? A sample code would be greatly appreciated.

Current part of Code

animation: {
  duration: 500,
  easing: "easeOutQuart",
  onComplete: function () {
    var ctx = this.chart.ctx;
    ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
    ctx.textAlign = 'center';
    ctx.textBaseline = 'bottom';

    this.data.datasets.filter(dataset => !dataset._meta[Object.keys(dataset._meta)[0]].hidden).forEach(function (dataset) {
      for (var i = 0; i < dataset.data.length; i++) {
        var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
        scale_max = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
        ctx.fillStyle = '#000';
        var y_pos = model.y - 5;
                  // Make sure data value does not get overflown and hidden
                  // when the bar's value is too close to max value of scale
                  // Note: The y value is reverse, it counts from top down
                  if ((scale_max - model.y) / scale_max >= 0.70)
                    y_pos = model.y + 20; 
                  ctx.fillText(addCommas(dataset.data[i]), model.x, y_pos);
                }
          });               
  }
}

I just got the code from this site so I'm not sure how to play or modify it. As far as I know this kind of feature is not discussed in the documentation of chart js.

expected output

if the value is 35,400 then it should be: 3 5, 4 0 0 (vertically)

1

There are 1 answers

3
Naren Murali On BEST ANSWER

After going through the requirement, I wrote this generic function for creating vertical labels, here is a demo of the vertical labeling function in action.

JSFiddle Demo

The parameter details of the vertical label function is described in detail below.

function verticalLabel(ctx, data, dataToSplit, topOffset, spaceBetween, commaGap) {
  var i = 0, prev = 0;
  for (x of dataToSplit.toString().split("").reverse()) {
    if (x.indexOf(",") > -1) {
      ctx.fillText(x, data.x + commaGap, prev - topOffset);
    } else {
      ctx.fillText(x, data.x, data.y - spaceBetween * i - topOffset);
      i++;
    }
    var prev = data.y - spaceBetween * i;
  }
}

Calling the function:

    this.datasets.forEach(function(dataset) {
      dataset.points.forEach(function(points) {
        console.log(points);
        verticalLabel(ctx, points, addCommas(points.value), 30, 10, 4);
      });
    })

Parameters:

  1. ctx - The variable containing the line (var ctx = document.getElementById("myChart1").getContext("2d"))

  2. data - This is the variable containing the label, value, x and y properties of the individual points in the chart.

  3. dataToSplit - Before passing in the data into the function, we might do some string manipulations to the data. We can pass the final manipulated string variable into this parameter and this will get converted into the vertical label. So in our above example, we pass the value of bar(which is nothing but data parameter of our function), through another function called addCommas() which will just added number separators into the value, finally this is passed to the main function which show the output of this result as a vertical number.

  4. topOffset - This parameter is used to set the distance of the number from the top of the point, this can have any number provided its of numerical datatype and its an integer!

  5. spaceBetween - This parameter is used to set the distance between the characters of the points value(data), this can have any number provided its of numerical datatype and its an integer! This parameter does not apply to the comma in the data.

  6. commaGap - This parameter is used to set the distance between the characters before the comma and the actual comma, you can think of it as increasing the legibility of the comma by increasing the space before the comma (E.g 9, can be represented as 9 ,), this can have any number provided its of numerical datatype and its an integer! This parameter does not apply to the comma in the data.