Plugins Chart.js display the values in the bar chart

1

Hi, I'm working with Chart.js to show different graphs, in the bar graph that the one that brings me the percent fulfilled I need to show the value on top of the bar, someone could help me, I think we have to work in the options with onComplete but I do not have the knowledge to do it.

var barChartData = {
  labels: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio"],

  datasets: [{

      fillColor: "#6b9dfa",
      strokeColor: "#ffffff",
      highlightFill: "#1864f2",
      highlightStroke: "#ffffff",
      data: [90, 30, 10, 80, 15, 5, 15]

    },
    {

      fillColor: "#e9e225",
      strokeColor: "#ffffff",
      highlightFill: "#ee7f49",
      highlightStroke: "#ffffff",
      data: [40, 50, 70, 40, 85, 55, 15]

    }

  ]

}
var ctx3 = document.getElementById("chart-rea3").getContext("2d");
window.myPie = new Chart(ctx3).Bar(barChartData, {
  responsive: true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.min.js"></script>
<canvas id="chart-rea3" class="pie"></canvas>
    
asked by Antonio Veliz 14.11.2017 в 16:51
source

1 answer

3

Based on this answer I created a options variable that contains the onAnimationComplete event and traverses each column by adding a text above with the value.

If you want another position, you have to modify the value of x e y in this line:

ctx.fillText(bar.value, bar.x, bar.y - 5);

Also I also put the option showTooltips: false so that when you pass the mouse does not show the information because it is already placed on top of the columns.

var barChartData = {
  labels: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio"],

  datasets: [{

      fillColor: "#6b9dfa",
      strokeColor: "#ffffff",
      highlightFill: "#1864f2",
      highlightStroke: "#ffffff",
      data: [90, 30, 10, 80, 15, 5, 15]

    },
    {

      fillColor: "#e9e225",
      strokeColor: "#ffffff",
      highlightFill: "#ee7f49",
      highlightStroke: "#ffffff",
      data: [40, 50, 70, 40, 85, 55, 15]

    }

  ]

}

var options = {
  responsive: true,
  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";

    this.datasets.forEach(function(dataset) {
      dataset.bars.forEach(function(bar) {
        ctx.fillText(bar.value, bar.x, bar.y - 5);
      });
    })
  }
};

var ctx3 = document.getElementById("chart-rea3").getContext("2d");
window.myPie = new Chart(ctx3).Bar(barChartData, options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.min.js"></script>
<canvas id="chart-rea3" class="pie"></canvas>
    
answered by 15.11.2017 / 09:47
source