0

I have this graph with 2 series (NFe, CTe). The x-axis data is grouped by type.

However, one of these data has a much greater value than the others. Example: 17000 and the other 150.

Problem

I would like to click on the x-axis value (as the arrow points), and remove it from the graph or have some way that I can show and hide a specific series value as it exists to show and hide the entire series.

My Code

$.ajax({
    url: '/Data',
    type: 'GET',
    success: function (data) {
        $(data.dados).each(function (index, item) {
            var labels = [];
            var dadosNFe = [];
            var dadosCTe = [];

            $(data.dados).each(function (index, item) {
                if (jQuery.inArray(item.Rotulo, rotulos) == -1) {
                    rotulos.push(item.Rotulo);
                }

                if (item.Grupo == "NFe") {
                    dadosNFe.push({ x: item.Rotulo, y: item.Valor });
                }
                if (item.Grupo == "CTe") {
                    dadosCTe.push({ x: item.Rotulo, y: item.Valor });
                }
            });

            const chartTotal = document.getElementById('totalDocumentosSEFAZ').getContext('2d');
            if (chart1) {
                chart1.destroy();
            }
            chart1 = new Chart(chartTotal , {
                type: tipo,
                data: {
                    labels: rotulos,
                    datasets: [
                        {
                            label: 'NFe',
                            fill: false,
                            data: dadosNFe,
                            borderColor: '#6666FF',
                            backgroundColor: '#6666FF',
                            tension: 0.1
                        },
                        {
                            label: 'CTe',
                            fill: false,
                            data: dadosCTe,
                            borderColor: '#FF6666',
                            backgroundColor: '#FF6666'
                        }
                    ]
                }
            });
        });
    }
});

Graph Example

Tiedt Tech
  • 719
  • 15
  • 46
  • maybe this [question](https://stackoverflow.com/questions/39517956/onclick-event-to-hide-dataset-chart-js-v2) will help you – Yago Biermann Mar 31 '22 at 16:03
  • @YagoBiermann I don't want to delete an entire series by clicking on its label. This is already native. I really want to exclude a specific item from the data so it doesn't appear anymore. – Tiedt Tech Mar 31 '22 at 17:55

1 Answers1

0

This can be done with the following onclick event handler. If a click occurs in the region below the chart, the function first toggles the visibility of the data that matches the x index. Then, it computes the new y.max and finally invokes chart.update().

document.getElementById('canvas').onclick = evt => {
  if (chart.scales['y'].getValueForPixel(evt.clientY) > 0) {
    return; 
  }
  const indexX = chart.scales['x'].getValueForPixel(evt.clientX);
  chart.toggleDataVisibility(indexX);
  chart.options.y.max = chart.data.datasets
    .map(ds => ds.data.map((v, i) => chart.getDataVisibility(i) ? v : 0))
    .flatMap(data => data)
    .reduce((max, v) => max > v ? max : v);
  chart.update();
};

For further information about getValueForPixel and toggleDataVisibility, please consult the Chart.js documentation.

Please take a look at below runnable code and see how it works. Click on on the desired x label to have the chart redrawn.

const chart = new Chart('canvas', {
  type: 'bar',
  data: {
    labels: ['A', 'B', 'C', 'D', 'E', 'F'],
    datasets: [{
        label: 'Dataset 1',
        data: [3, 9, 7, 150, 9, 2],
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgb(255, 99, 132)',
        fill: false
      },
      {
        label: 'Dataset 2',
        data: [4, 8, 12, 145, 6, 4],
        backgroundColor: 'rgba(132, 99, 255, 0.2)',
        borderColor: 'rgb(132, 99, 255)',
        fill: false
      }
    ]
  },
  options: {
    y: {}
  }
});

const canvas = document.getElementById('canvas');
canvas.onclick = evt => {
  if (chart.scales['y'].getValueForPixel(evt.clientY) > 0) {
    return; 
  }
  const indexX = chart.scales['x'].getValueForPixel(evt.clientX);
  chart.toggleDataVisibility(indexX);
  chart.options.y.max = chart.data.datasets
    .map(ds => ds.data.map((v, i) => chart.getDataVisibility(i) ? v : 0))
    .flatMap(data => data)
    .reduce((max, v) => max > v ? max : v);
  chart.update();
};

canvas.onmousemove = evt => {
  const v = chart.scales['y'].getValueForPixel(evt.clientY);
  const indexX = chart.scales['x'].getValueForPixel(evt.clientX)
  canvas.style.cursor = v < 0 && indexX >= 0 ? 'pointer' : 'default';
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="canvas" height="80"></canvas>
uminder
  • 23,831
  • 5
  • 37
  • 72