Is it possible in chartjs to hide certain dataset legends?

一笑奈何 提交于 2020-05-10 07:04:37

问题


Is it possible to only hide certain dataset legends in chartjs? I know it is possible to hide all with

options: {
    legend: {
        display: false

回答1:


Short answer: Yes it is possible. Unfortunately it's not quite as simple as the developers could make it.

If you know what the text value of the item being displayed in the legend is, then you can filter that out. After reading through the Chart.js docs I found the section Legend Label Configuration that details a filter function that can be used to "filter out the legend items", although this function must be set on the parent chart options object, not as an option on the dataset itself:

const chart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        legend: {
            labels: {
                filter: function(item, chart) {
                    // Logic to remove a particular legend item goes here
                    return !item.text.includes('label to remove');
                }
            }
        }
    }
});

Now it appears each time the data changes and the chart is updated via chart.update() this filter function is called.

For convenience I have set this up in a jsfiddle for you to play with.

Note: This solution was designed around the API for version 2.7.1 of ChartJS. Future versions may improve the control over dataset legend labels.




回答2:


First No official example of this issue under chart.js docs.

How to filter by value (Hide all legends for a value greater than 1000)

Filters legend items out of the legend. Receives 2 parameters, a Legend Item and the chart data. https://www.chartjs.org/docs/latest/configuration/legend.html#legend-label-configuration

basic example - "works like magic":

Data:

  var data = {
    labels: ["Africa", "Asia", "Europe"],
    datasets: [{
      label: "Population (millions)",
      backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f"],
      data: [1000,1500,2000]
    }]
  };

The "trick" - get the array of values:

data.datasets[0]

Like this i get the data array.

Next - The filter loop throw data - Each time i get the current value by index. Basic Array idea: How to get value at a specific index of array In JavaScript?

var index = legendItem.index; /* 0..1...2 */
var currentDataValue =  data.datasets[0].data[index]; /* 1000...1500...2000 */

if "consept"

Show all legends:

if (true){
  return true;
}

And this hide all legends

if (false){
  return true;
}

So add any if statement you want (data value in our case):

if (currentDataValue > 1000){
  return true;
}

Complete example:

Hide legend if the value is greater than 1,000:

var data = {
  labels: ["Africa", "Asia", "Europe"],
  datasets: [{
    label: "Population (millions)",
    backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f"],
    data: [1000,1500,2000]
  }]
};

var options = {
  responsive: true,
  title: {
    text: 'Hide africa legened (Greater than 1000)',
    position: 'top',
    display: true
  },
  legend: {
    display: true,
    labels: {
      /* filter */
      filter: function(legendItem, data) {
        /* filter already loops throw legendItem & data (console.log) to see this idea */
        var index = legendItem.index;
        var currentDataValue =  data.datasets[0].data[index];
        console.log("current value is: " + currentDataValue)
        if (currentDataValue > 1000)
        {
          return true; //only show when the label is cash
        }
      },
      /* generateLabels */
      generateLabels(chart) {
        const data = chart.data;
        if (data.labels.length && data.datasets.length) {
          /* inner loop throw lables */
          return data.labels.map((label, i) => {
            var backgroundColor = data.datasets[0].backgroundColor[i];
            return {
              text: label + " | " + data.datasets[0].data[i],
              fillStyle: backgroundColor,
              // Extra data used for toggling the correct item
              index: i
            };
          });
        }
        return [];
      }

    },

  },
  scales: {
    xAxes: [{
      display: true
    }],
    yAxes: [{
      display: true
    }]
  }
};


new Chart(document.getElementById("chart"), {
  type: 'pie',
  data: data,
  options: options
});
<canvas id="chart" width="800" height="450"></canvas>
   
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

By the way in the example above i also use generateLabels idea (Add the value next to label text).



来源:https://stackoverflow.com/questions/47084144/is-it-possible-in-chartjs-to-hide-certain-dataset-legends

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!