How to display chart values in chartJS without mouseover?

Asked

Viewed 1,329 times

1

var chartData = {
    labels: [<?php echo html_entity_decode($nomes) ?>],
    datasets: [{
        label: 'Desempenho global (Todas limpezas efetuadas em <?php echo $anoAvaliado ?>)',
        data: [<?php foreach($limpezasAnuais as $limpeza){ echo $limpeza.",";} ?>],
        backgroundColor: [<?php foreach ($cores as $cor){echo "\"" . $cor . "\",";} ?>],
        borderWidth: 1
    }]
}
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    showTooltips: false,
    data: {
        labels: [<?php echo html_entity_decode($nomes) ?>],
        datasets: [{
            label: 'Desempenho global (Todas limpezas efetuadas em <?php echo $anoAvaliado ?>)',
            data: [<?php foreach($limpezasAnuais as $limpeza){ echo $limpeza.",";} ?>],
            backgroundColor: [<?php foreach ($cores as $cor){echo "\"" . $cor . "\",";} ?>],
            borderWidth: 1
        }]
    },
    options: {
        scales: {

            xAxes: [{
                ticks: {
                    beginAtZero: false
                }

            }]

        }
    }
});

inserir a descrição da imagem aqui

1 answer

2


You can user the events Chartjs provides. For example, for the chart to respond only to click events, you can use:

options: {
        //Este gráfico não responderá ao mousemove, etc
        events: ['click']
}

To leave the Tooltip always visible in version ChartJs > 2.1.5 you can control through the property of the options. Remembering that you need to register the plug-in before initializing the chart.

Source

Chart.pluginService.register({
  beforeRender: function(chart) {
    if (chart.config.options.showAllTooltips) {
      chart.pluginTooltips = [];
      chart.config.data.datasets.forEach(function(dataset, i) {
        chart.getDatasetMeta(i).data.forEach(function(sector, j) {
          chart.pluginTooltips.push(new Chart.Tooltip({
            _chart: chart.chart,
            _chartInstance: chart,
            _data: chart.data,
            _options: chart.options.tooltips,
            _active: [sector]
          }, chart));
        });
      });
      chart.options.tooltips.enabled = false;
    }
  },
  afterDraw: function(chart, easing) {
    if (chart.config.options.showAllTooltips) {
      if (!chart.allTooltipsOnce) {
        if (easing !== 1)
          return;
        chart.allTooltipsOnce = true;
      }


      chart.options.tooltips.enabled = true;
      Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
        tooltip.initialize();
        tooltip.update();
        tooltip.pivot();
        tooltip.transition(easing).draw();
      });
      chart.options.tooltips.enabled = false;
    }
  }
});

Then use

options: {
    showAllTooltips: true
}

Example

var canvas = document.getElementById('myChart');
Chart.pluginService.register({
  beforeRender: function(chart) {
    if (chart.config.options.showAllTooltips) {
      chart.pluginTooltips = [];
      chart.config.data.datasets.forEach(function(dataset, i) {
        chart.getDatasetMeta(i).data.forEach(function(sector, j) {
          chart.pluginTooltips.push(new Chart.Tooltip({
            _chart: chart.chart,
            _chartInstance: chart,
            _data: chart.data,
            _options: chart.options.tooltips,
            _active: [sector]
          }, chart));
        });
      });
      chart.options.tooltips.enabled = false;
    }
  },
  afterDraw: function(chart, easing) {
    if (chart.config.options.showAllTooltips) {
      if (!chart.allTooltipsOnce) {
        if (easing !== 1)
          return;
        chart.allTooltipsOnce = true;
      }

      chart.options.tooltips.enabled = true;
      Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
        tooltip.initialize();
        tooltip.update();
        tooltip.pivot();
        tooltip.transition(easing).draw();
      });
      chart.options.tooltips.enabled = false;
    }
  }
});

var data = {
  labels: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho"],
  datasets: [{
    label: "Meu dataset",
    backgroundColor: "rgba(255,99,132,0.2)",
    borderColor: "rgba(255,99,132,1)",
    borderWidth: 2,
    hoverBackgroundColor: "rgba(255,99,132,0.4)",
    hoverBorderColor: "rgba(255,99,132,1)",
    data: [65, 59, 20, 81, 56, 55, 40],
  }]
};

var myBarChart = Chart.Bar(canvas, {
  data: data,
  options: {
    showAllTooltips: true,
    tooltips: {
      callbacks: {
        title: function(tooltipItems, data) {
          return '';
        },
        label: function(tooltipItem, data) {
          var datasetLabel = '';
          var label = data.labels[tooltipItem.index];
          return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
        }
      }
    }
  }
});
<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/2.3.0/Chart.js"></script>

<canvas id="myChart" height="230" width="680"></canvas>

  • I understand Netinho, but isn’t it possible that the value is displayed without me having to click and without needing the mouseover? I need it to work like this to get in the PDF.

  • @Viniciusavanzi is possible yes. I changed the answer. Watch out. Att.

  • Just one more thing! Can you show only the value? It is displaying the names and also the legend.I wanted to post the print here but I still don’t know how to move the forum, rsrsrsrsr

  • @Viniciusavanzi I changed again the answer to display only the value. If you have more questions, check the plugin documentation: http://www.chartjs.org/docs/latest/ If the answer suits you, vote for it to help others. Att.

  • What did you do? Changed the plugin registration ? Thank you! How do I vote in response ?

  • @Viniciusavanzi I put in option the callbacks function. For you to vote as the answer accepted click on 'v' gives answer. Check the print here: https://uploaddeimagens.com.br/imagens/capturr-png-6347e280-f9dd-416e-942f-97b650b40ca1

  • @Viniciusavanzi O stack tem um tour onde você poderá sanar suas dúvidas como voto útil, voto de aceite para resposta, conduta e como elaborar perguntas e resposta. Follow the link https://answall.com/tour Att.

  • 1

    Thank you so much for helping @Netinho Santos. It worked!!! God bless you!

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.