skip to Main Content

I have this very useful chart but my problem the client want percentage label must display I have attach image below of what what I want.

enter image description here

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<body>

<canvas id="myChart" style="width:100%;max-width:600px"></canvas>

<script>
const xValues = ["Italy", "France", "Spain", "USA", "Argentina"];
const yValues = [55, 49, 44, 24, 15];
const barColors = ["red", "green","blue","orange","brown"];

new Chart("myChart", {
  type: "bar",
  data: {
    labels: xValues,
    datasets: [{
      backgroundColor: barColors,
      data: yValues
    }]
  },
  options: {
    legend: {display: false},
    title: {
      display: true,
      text: "World Wine Production 2018"
    }
  }
});
</script>

</body>
</html>

2

Answers


  1. To show the percentage on the top of each bar, you can use the datalabel plugin with your charts. It helps to add the Y-Axis actual count on the top of each bar. Even, you can modify its behavior too.

    Giving an example link, from where you can also get a better understanding of it. [Video Link]

    Login or Signup to reply.
  2. You can use onComplete hook to draw/write these values after chart animation is fully rendered. And then use ctx.fillText() to customise how you prefer.

    const xValues = ["Italy", "France", "Spain", "USA", "Argentina"];
    const yValues = [55, 49, 44, 24, 15];
    const barColors = ["red", "green","blue","orange","brown"];
    const total = yValues.reduce((acc, val) => acc + val, 0);
    new Chart("myChart", {
      type: "bar",
      data: {
        labels: xValues,
        datasets: [{
          backgroundColor: barColors,
          data: yValues
        }]
      },
    options: {
        legend: {display: false},
        title: {
          display: true,
          text: "World Wine Production 2018"
        },
        animation: {
          onComplete: function () {
            const ctx = this.chart.ctx;
            ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
            ctx.fillStyle = "red";
            ctx.textAlign = 'center';
            ctx.textBaseline = 'bottom';
            this.data.datasets.forEach(function (dataset) {
              for (let i = 0; i < dataset.data.length; i++) {
    const model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                ctx.fillText(dataset.data[i], model.x, model.y - 5);
                ctx.fillText("%", model.x + 15, model.y - 5);
              }
            });
          }
        }
      }
    });
    

    https://cdpn.io/pen/debug/gOJwWLb?authentication_hash=LQkExZebvzdA

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search