javascript – Chart.js更改图例切换行为

我有一张来自chart.js的雷达图表.目前,它加载了所有可行的数据,并且支持图例通过单击图例标签来表现,该标签可以切换与图例相关联的数据.我希望能够点击图例标签,然后切换所有其他关闭并可能引入“全部”选项?这可以用chart.js吗?

以下是我的图表现在的样子:

var chartata = { 
labels: [ 
"Strategic Development and Ownership", 
"Driving change through others", 
"Exec disposition", 
"Commercial Acumen", 
"Develops High Performance Teams", 
"Innovation and risk taking", 
"Global leadership", 
"Industry leader" 
]}; 

var ctx = $("#allRadarData"); 

var config = { 
    type: 'radar', 
    data: chartata,     
    animationEasing: 'linear',
        options: {           
         legend: {
            fontSize: 10,
            display: true,
            itemWidth: 150,
            position: 'bottom',
            fullWidth: true,
            labels: {
                fontColor: 'rgb(0,0,0)',
                BoxWidth: 10,
                padding: 20
            },
        },
         tooltips: {
            enabled: true
        },
        scale: {
            ticks: {
                fontSize: 15,
                beginAtZero: true,
                stepSize: 1,
                max: 5
            }
        } 

    },
}, 

LineGraph = new Chart(ctx, config); 

var colorArray = [

    ["#f44336", false],
    ["#E91E63", false],
    ["#9C27B0", false],
    ["#673AB7", false],
    ['#3F51B5', false],
    ["#607D8B", false]
];


for (var i in data) { 
    tmpscore=[]; 
    tmpscore.push(data[i].score1); 
    tmpscore.push(data[i].score2); 
    tmpscore.push(data[i].score3); 
    tmpscore.push(data[i].score4); 
    tmpscore.push(data[i].score5); 
    tmpscore.push(data[i].score6); 
    tmpscore.push(data[i].score7); 
    tmpscore.push(data[i].score8); 

    var color, done = false;
    while (!done) {
        var test = colorArray[parseInt(Math.random() * 10)];
        if (!test[1]) {
            color = test[0];
            colorArray[colorArray.indexOf(test)][1] = true;
            done = !done;
        }
    }


newDataset = { 
    label: data[i].firstName+' '+data[i].lastName, 
     borderColor: color,
    backgroundColor: "rgba(0,0,0,0)", 
    data: tmpscore, 
}; 

config.data.datasets.push(newDataset); 

} 

LineGraph.update(); 
},  
}); 

});

解决方法:

要反转图例标签单击行为的方式,可以使用图例onClick选项来实现新的单击逻辑.下面是一个示例,它将为您提供所需的行为.请注意,在此实现中,如果单击已隐藏的标签,它将取消隐藏它,并隐藏所有其他标签.

function(e, legendItem) {
  var index = legendItem.datasetIndex;
  var ci = this.chart;
  var alreadyHidden = (ci.getDatasetMeta(index).hidden === null) ? false : ci.getDatasetMeta(index).hidden;

  ci.data.datasets.forEach(function(e, i) {
    var Meta = ci.getDatasetMeta(i);

    if (i !== index) {
      if (!alreadyHidden) {
        Meta.hidden = Meta.hidden === null ? !Meta.hidden : null;
      } else if (Meta.hidden === null) {
        Meta.hidden = true;
      }
    } else if (i === index) {
      Meta.hidden = null;
    }
  });

  ci.update();
};

这也是working example.

但是,如果您想要一个更复杂的逻辑,当前至少有一个其他标签可见时,它将取消隐藏当前隐藏的标签,那么您可以使用以下实现.

function(e, legendItem) {
  var index = legendItem.datasetIndex;
  var ci = this.chart;
  var alreadyHidden = (ci.getDatasetMeta(index).hidden === null) ? false : ci.getDatasetMeta(index).hidden;       
  var anyOthersAlreadyHidden = false;
  var allOthersHidden = true;

  // figure out the current state of the labels
  ci.data.datasets.forEach(function(e, i) {
    var Meta = ci.getDatasetMeta(i);

    if (i !== index) {
      if (Meta.hidden) {
        anyOthersAlreadyHidden = true;
      } else {
        allOthersHidden = false;
      }
    }
  });

  // if the label we clicked is already hidden 
  // then we Now want to unhide (with any others already unhidden)
  if (alreadyHidden) {
    ci.getDatasetMeta(index).hidden = null;
  } else { 
    // otherwise, lets figure out how to toggle visibility based upon the current state
    ci.data.datasets.forEach(function(e, i) {
      var Meta = ci.getDatasetMeta(i);

      if (i !== index) {
        // handles logic when we click on visible hidden label and there is currently at least
        // one other label that is visible and at least one other label already hidden
        // (we want to keep those already hidden still hidden)
        if (anyOthersAlreadyHidden && !allOthersHidden) {
          Meta.hidden = true;
        } else {
          // toggle visibility
          Meta.hidden = Meta.hidden === null ? !Meta.hidden : null;
        }
      } else {
        Meta.hidden = null;
      }
    });
  }

  ci.update();
}

这个替代实现也是working example.

要在特定代码中使用它,只需使用onClick属性将其放在图表的图例配置中.

var config = { 
  type: 'radar', 
  data: chartata,   
  animationEasing: 'linear',
    options: {       
     legend: {
      fontSize: 10,
      display: true,
      itemWidth: 150,
      position: 'bottom',
      fullWidth: true,
      labels: {
        fontColor: 'rgb(0,0,0)',
        BoxWidth: 10,
        padding: 20
      },
      onClick: function(e, legendItem) {
        var index = legendItem.datasetIndex;
        var ci = this.chart;
        var alreadyHidden = (ci.getDatasetMeta(index).hidden === null) ? false : ci.getDatasetMeta(index).hidden;

        ci.data.datasets.forEach(function(e, i) {
          var Meta = ci.getDatasetMeta(i);

          if (i !== index) {
            if (!alreadyHidden) {
              Meta.hidden = Meta.hidden === null ? !Meta.hidden : null;
            } else if (Meta.hidden === null) {
              Meta.hidden = true;
            }
          } else if (i === index) {
            Meta.hidden = null;
          }
        });

        ci.update();
      },
    },
     tooltips: {
      enabled: true
    },
    scale: {
      ticks: {
        fontSize: 15,
        beginAtZero: true,
        stepSize: 1,
        max: 5
      }
    }
  },
}, 

目前尚不清楚你想要’all’选项有什么行为,但你可以使用legend.labels.generateLabels选项来欺骗Chart.js添加’all’标签(你将不得不修改上面的内容) onClick逻辑来处理这个想法.

但是,我认为更好的解决方案是在chart.js画布之外实现您自己的链接或按钮,以显示/隐藏所有数据集.查看Chart.js radar sample page以了解它们如何使用图表操作绑定按钮.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...