comment afficher les valeurs des données sur le Graphique.js

je voudrais demander si c'est possible en utilisant le graphique.js pour afficher les valeurs des données? Je veux imprimer le graphique.

Merci pour tout conseil.

68
demandé sur FuSsA 2015-07-26 00:33:35

11 réponses

edit en retard: il y a un plugin officiel pour Chart.js 2.7.0+ pour faire ceci: https://github.com/chartjs/chartjs-plugin-datalabels

réponse originale:

vous pouvez boucler la boucle à travers les points / barres onAnimationComplete et afficher les valeurs


"Aperçu de la 151950920"

enter image description here


HTML

<canvas id="myChart1" height="300" width="500"></canvas>
<canvas id="myChart2" height="300" width="500"></canvas>

Script

var chartData = {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [
        {
            fillColor: "#79D1CF",
            strokeColor: "#79D1CF",
            data: [60, 80, 81, 56, 55, 40]
        }
    ]
};

var ctx = document.getElementById("myChart1").getContext("2d");
var myLine = new Chart(ctx).Line(chartData, {
    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.points.forEach(function (points) {
                ctx.fillText(points.value, points.x, points.y - 10);
            });
        })
    }
});

var ctx = document.getElementById("myChart2").getContext("2d");
var myBar = new Chart(ctx).Bar(chartData, {
    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);
            });
        })
    }
});

Fiddle - http://jsfiddle.net/uh9vw0ao /

92
répondu potatopeelings 2018-01-09 00:39:23

Voici une version mise à jour de Chart.js 2.3

Sep 23, 2016: Édité mon code pour travailler avec v2.3 pour les deux line/type de barre.

Important: même si vous n'avez pas besoin de l'animation, ne changez pas l'option de durée à 0, sinon vous obtiendrez chartInstance.le contrôleur est une erreur non définie.

var chartData = {
    labels: ["January", "February", "March", "April", "May", "June"],
        datasets: [
            {
                fillColor: "#79D1CF",
                strokeColor: "#79D1CF",
                data: [60, 80, 81, 56, 55, 40]
            }
        ]
    };

var opt = {
    events: false,
    tooltips: {
        enabled: false
    },
    hover: {
        animationDuration: 0
    },
    animation: {
        duration: 1,
        onComplete: function () {
            var chartInstance = this.chart,
                ctx = chartInstance.ctx;
            ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
            ctx.textAlign = 'center';
            ctx.textBaseline = 'bottom';

            this.data.datasets.forEach(function (dataset, i) {
                var meta = chartInstance.controller.getDatasetMeta(i);
                meta.data.forEach(function (bar, index) {
                    var data = dataset.data[index];                            
                    ctx.fillText(data, bar._model.x, bar._model.y - 5);
                });
            });
        }
    }
};
 var ctx = document.getElementById("Chart1"),
     myLineChart = new Chart(ctx, {
        type: 'bar',
        data: chartData,
        options: opt
     });
<canvas id="myChart1" height="300" width="500"></canvas>
63
répondu Ross 2016-11-02 02:43:26

cette option d'animation fonctionne pour 2.1.3 sur un diagramme à barres.

légèrement modifié @Ross answer

animation: {
duration: 0,
onComplete: function () {
    // render the value of the chart above the bar
    var ctx = this.chart.ctx;
    ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
    ctx.fillStyle = this.chart.config.options.defaultFontColor;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'bottom';
    this.data.datasets.forEach(function (dataset) {
        for (var i = 0; i < dataset.data.length; i++) {
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
            ctx.fillText(dataset.data[i], model.x, model.y - 5);
        }
    });
}}
27
répondu Aaron Hudon 2016-09-17 19:27:31

je pense que la meilleure option pour le faire dans chartJS v2.x est en utilisant un plugin, donc vous n'avez pas un grand bloc de code dans les options. En outre, il empêche les données de disparaître en vol stationnaire au-dessus d'une barre.

i. e. il suffit d'utiliser ce code, qui enregistre un plugin qui ajoute le texte après que le graphique est dessiné.

Chart.pluginService.register({
    afterDraw: function(chartInstance) {
        var ctx = chartInstance.chart.ctx;

        // render the value of the chart above the bar
        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';

        chartInstance.data.datasets.forEach(function (dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                ctx.fillText(dataset.data[i], model.x, model.y - 2);
            }
        });
  }
});
17
répondu David 2016-09-17 16:04:32

basé sur la réponse de @Ross pour le graphique.js 2.0 et plus, j'ai dû inclure un petit tweak pour me prémunir contre l'affaire quand les hauteurs de la barre viennent trop choisi à la limite de l'échelle.

Example

l'attribut animation de l'option du diagramme à barres:

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.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 = '#444';
                        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.93)
                            y_pos = model.y + 20; 
                        ctx.fillText(dataset.data[i], model.x, y_pos);
                    }
                });               
            }
        }
16
répondu Hung Tran 2016-08-05 21:01:09

après cette bonne réponse ,j'utiliserais ces options pour un diagramme à barres:

var chartOptions = {
    animation: false,
    responsive : true,
    tooltipTemplate: "<%= value %>",
    tooltipFillColor: "rgba(0,0,0,0)",
    tooltipFontColor: "#444",
    tooltipEvents: [],
    tooltipCaretSize: 0,
    onAnimationComplete: function()
    {
        this.showTooltip(this.datasets[0].bars, true);
    }
};

window.myBar = new Chart(ctx1).Bar(chartData, chartOptions);

Bar Chart

cela utilise encore le système tooltip et ses avantages (positionnement automatique, templating,...) mais Cacher les décorations (couleur de fond, caret, ...)

7
répondu Pierre de LESPINAY 2017-05-23 11:47:28

de la carte.échantillons js (file Chart.js-2.4.0 / samples / data_labelling.html):

`` // Définition d'un plugin pour fournir des étiquettes de données

    Chart.plugins.register({
        afterDatasetsDraw: function(chartInstance, easing) {
            // To only draw at the end of animation, check for easing === 1
            var ctx = chartInstance.chart.ctx;

            chartInstance.data.datasets.forEach(function (dataset, i) {
                var meta = chartInstance.getDatasetMeta(i);
                if (!meta.hidden) {
                    meta.data.forEach(function(element, index) {
                        // Draw the text in black, with the specified font
                        ctx.fillStyle = 'rgb(0, 0, 0)';

                        var fontSize = 16;
                        var fontStyle = 'normal';
                        var fontFamily = 'Helvetica Neue';
                        ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);

                        // Just naively convert to string for now
                        var dataString = dataset.data[index].toString();

                        // Make sure alignment settings are correct
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';

                        var padding = 5;
                        var position = element.tooltipPosition();
                        ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
                    });
                }
            });
        }
    });

""

6
répondu Radek Dest 2017-02-22 12:39:20

je recommande d'utiliser ce plugin: https://github.com/chartjs/chartjs-plugin-datalabels

Les étiquettes

peuvent être ajoutées à vos charts simplement en important le plugin dans le fichier js par exemple:

import 'chartjs-plugin-datalabels'

et peut être affiné en utilisant ces docs: https://chartjs-plugin-datalabels.netlify.com/options.html

5
répondu DavidX 2017-10-18 04:46:18

édité un peu la réponse de @ajhuddy. Seulement pour les graphiques à barres . Ma version ajoute:

  • Fondu dans l'animation pour les valeurs.
  • empêcher la coupure en positionnant la valeur à l'intérieur de la barre si la barre est trop haute.
  • pas de clignement.

Example

inconvénient: en vol stationnaire au-dessus d'une barre qui a une valeur à l'intérieur de lui la valeur pourrait sembler un peu irrégulier. Je n'ai pas trouvé de solution pour désactiver les effets de vol stationnaire. Il peut également avoir besoin de peaufiner en fonction de vos paramètres.

Configuration:

bar: {
  tooltips: {
    enabled: false
  },
  hover: {
    animationDuration: 0
  },
  animation: {
    onComplete: function() {
      this.chart.controller.draw();
      drawValue(this, 1);
    },
    onProgress: function(state) {
      var animation = state.animationObject;
      drawValue(this, animation.currentStep / animation.numSteps);
    }
  }
}

Helpers:

// Font color for values inside the bar
var insideFontColor = '255,255,255';
// Font color for values above the bar
var outsideFontColor = '0,0,0';
// How close to the top edge bar can be before the value is put inside it
var topThreshold = 20;

var modifyCtx = function(ctx) {
  ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
  ctx.textAlign = 'center';
  ctx.textBaseline = 'bottom';
  return ctx;
};

var fadeIn = function(ctx, obj, x, y, black, step) {
  var ctx = modifyCtx(ctx);
  var alpha = 0;
  ctx.fillStyle = black ? 'rgba(' + outsideFontColor + ',' + step + ')' : 'rgba(' + insideFontColor + ',' + step + ')';
  ctx.fillText(obj, x, y);
};

var drawValue = function(context, step) {
  var ctx = context.chart.ctx;

  context.data.datasets.forEach(function (dataset) {
    for (var i = 0; i < dataset.data.length; i++) {
      var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
      var textY = (model.y > topThreshold) ? model.y - 3 : model.y + 20;
      fadeIn(ctx, dataset.data[i], model.x, textY, model.y > topThreshold, step);
    }
  });
};
4
répondu Janne Annala 2016-10-06 09:52:42

D'après mon expérience, une fois que vous avez inclus le chartjs-plugin-datalabels plugin (assurez-vous de placer la balise <script> après la carte.js tag sur votre page), vos graphiques commencent à afficher des valeurs.

si vous choisissez alors vous pouvez le personnaliser pour s'adapter à vos besoins. La personnalisation est clairement documentée ici mais, fondamentalement, le format est comme cet exemple hypothétique:

var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: yourDataObject,
    options: {
        // other options
        plugins: {
            datalabels: {
                anchor = 'end',
                align = 'top',
                // and if you need to format how the value is displayed...
                formatter: function(value, context) {
                    return GetValueFormatted(value);
                }
            }
        }
    }
});
3
répondu Soma Mbadiwe 2018-01-25 00:36:59

si vous utilisez le plugin chartjs-plugin-datalabels alors l'objet options de code suivant vous aidera

assurez-vous d'importer import 'chartjs-plugin-datalabels'; dans votre fichier dactylographié ou d'ajouter une référence à <script src="chartjs-plugin-datalabels.js"></script> dans votre fichier javascript.

options: {
    maintainAspectRatio: false,
    responsive: true,
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true,
        }
      }]
    },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'top',
        formatter: Math.round,
        font: {
          weight: 'bold'
        }
      }
    }
  }
2
répondu Karthik 2018-05-17 10:55:02