Maison  >  Questions et réponses  >  le corps du texte

Comment afficher du texte sur un graphique à barres ChartJS ?

Je dois écrire du texte dans une barre d'un graphique à l'aide de chart.js

var ctx = document.getElementById("myChart");
 var myChart = new Chart(ctx, {
     type: 'bar',
     data:data,
     options: {           
         scales: {
             yAxes: [{
                 ticks: {
                     beginAtZero:true
                 }
             }]
         }
     },
     responsive : true,
     showTooltips : false,
     showInlineValues : true,
     centeredInllineValues : true,
     tooltipCaretSize : 0,
     tooltipTemplate : "<%= value %>"
 });

Le code ci-dessus ne fonctionne pas...

J'ai besoin de quelque chose comme ça :

P粉578343994P粉578343994332 Il y a quelques jours596

répondre à tous(2)je répondrai

  • P粉803527801

    P粉8035278012023-10-24 13:35:12

    Si vous souhaitez afficher le texte centré pour chaque élément, il existe un moyen plus simple :

    Chart.helpers.each(meta.data.forEach(function (bar, index) {
        var centerPoint = bar.getCenterPoint();
        ctx.fillText(dataset.data[index], centerPoint.x, centerPoint.y));
    }),this)

    Il semble que 'getCenterPoint' ne soit pas disponible dans la version 2.1.3 (celle que vous avez utilisée dans votre exemple). Je l'ai essayé avec 2.5.0 et ça marche

    répondre
    0
  • P粉362071992

    P粉3620719922023-10-24 11:28:29

    Ajoutez ce code à votre objet options :

    animation: {
      onComplete: function () {
        var chartInstance = this.chart;
        var ctx = chartInstance.ctx;
        console.log(chartInstance);
        var height = chartInstance.controller.boxes[0].bottom;
        ctx.textAlign = "center";
        Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) {
          var meta = chartInstance.controller.getDatasetMeta(i);
          Chart.helpers.each(meta.data.forEach(function (bar, index) {
            ctx.fillText(dataset.data[index], bar._model.x, height - ((height - bar._model.y) / 2));
          }),this)
        }),this);
      }
    }

    https://jsfiddle.net/h4p8f5xL/

    Mise à jour 2

    Entourez la toile d'un contenant de la largeur et de la hauteur souhaitées

    <div style="width: 100%; height: 500px">
        <canvas id="myChart" width="400" height="400"></canvas>
    </div>

    Et ajoutez ce qui suit à votre objet d'options

    // Boolean - whether or not the chart should be responsive and resize when the browser does.
    responsive: true,
    // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
    maintainAspectRatio: false,

    répondre
    0
  • Annulerrépondre