提问者:小点点

unh单击按钮时选中图例


我已经用chart.js创建了一个图表,并且我有onclick事件用于图例。我想要显示所有的图例而不是删除线

null

 const totalizer = {
    id: 'totalizer',
    beforeUpdate: chart => {
        let totals = {}
        let utmost = 0

            chart.data.datasets.forEach((dataset, datasetIndex) => {
                if (chart.isDatasetVisible(datasetIndex)) {
                    utmost = datasetIndex
                        dataset.data.forEach((value, index) => {
                            totals[index] = (totals[index] || 0) + value
                        })
                }
            })
            chart.$totalizer = {
            totals: totals,
            utmost: utmost
        }
    }
}

new Chart('chart', {
  type: 'horizontalBar',
  data: {
    labels: ['Brut', 'Net imposable', 'Net'],
    datasets: [{"data":[10,20,10],"label":"1st Presentation \/ Meeting","backgroundColor":"#7B68EE"},{"data":[109,82,22],"label":"Hold\/Uncategorized","backgroundColor":"#B0C4DE"},{"data":[4,14,1],"label":"SGL","backgroundColor":"#F4A460"},{"data":[1,0,0],"label":"PGL","backgroundColor":"#BC8F8F"},{"data":[1,8,1],"label":"QO under evaluation","backgroundColor":"#2E8B57"},{"data":[38,37,16],"label":"Follow-On Meetings","backgroundColor":"#6495ED"},{"data":[9,6,0],"label":"MGL","backgroundColor":"#FFA500"},{"data":[6,32,0],"label":"Identified Opportunities","backgroundColor":"#6B8E23"},{"data":[0,2,0],"label":"RGL","backgroundColor":"#DEB887"}],"yearly":[{"data":[2],"label":"RGL","backgroundColor":"#DEB887"},{"data":[40],"label":"1st Presentation \/ Meeting","backgroundColor":"#7B68EE"},{"data":[10],"label":"QO under evaluation","backgroundColor":"#2E8B57"},{"data":[1],"label":"PGL","backgroundColor":"#BC8F8F"},{"data":[38],"label":"Identified Opportunities","backgroundColor":"#6B8E23"},{"data":[19],"label":"SGL","backgroundColor":"#F4A460"},{"data":[213],"label":"Hold\/Uncategorized","backgroundColor":"#B0C4DE"},{"data":[15],"label":"MGL","backgroundColor":"#FFA500"},{"data":[91],"label":"Follow-On Meetings","backgroundColor":"#6495ED"}],"user":[{"data":[0,1,0,0,2,14,7,0,1,2,0,2,1,4,0,1,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"Identified Opportunities","backgroundColor":"#6B8E23"},{"data":[5,2,0,9,3,0,2,6,5,0,3,0,0,0,2,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0],"label":"1st Presentation \/ Meeting","backgroundColor":"#7B68EE"},{"data":[149,2,39,0,11,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],"label":"Hold\/Uncategorized","backgroundColor":"#B0C4DE"},{"data":[0,2,0,2,0,0,6,4,1,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"SGL","backgroundColor":"#F4A460"},{"data":[2,1,0,0,4,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],"label":"QO under evaluation","backgroundColor":"#2E8B57"},{"data":[7,42,0,21,8,0,5,1,0,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"Follow-On Meetings","backgroundColor":"#6495ED"},{"data":[0,3,0,6,0,0,1,0,0,2,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"label":"MGL","backgroundColor":"#FFA500"},{"data":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"PGL","backgroundColor":"#BC8F8F"},{"data":[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"RGL","backgroundColor":"#DEB887"}]},"filter":{"weekly":["Week 1","Week 2","Week 3","Week 4"]
  },
  options: {
    scales: {
      xAxes: [{
        stacked: true
       
      }],
      yAxes: [{
        stacked: true
      }]
    },
    legend: {
       onClick: 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();
        },
    display: true,
    position: "right",
    labels: {
		filter: function(item, chart) {
          // Logic to remove a particular legend item goes here
          return !item.text.includes('Total');
        },
      fontColor: "black",
      boxWidth: 12,
      fontFamily: "Raleway-medium"
    }
  },
    plugins: {
      datalabels: {
        formatter: (value, ctx) => {
          const total = ctx.chart.$totalizer.totals[ctx.dataIndex]
          return total.toLocaleString('fr-FR', {
             style: 'currency',
            currency: 'EUR'
          })
        },
        align: 'end',
        anchor: 'end',
        display: function(ctx) {
          return ctx.datasetIndex === ctx.chart.$totalizer.utmost
        }
      }
    }
  },
  plugins: [totalizer]
});

$('.reset').click(function(){
//chart.ctx.legend.reset();
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>

<button class='reset'>Reset</button>
<canvas id="chart" width="100" height="50"></canvas>

null

无法显示按钮单击时选择的图例


共2个答案

匿名用户

这里是图例的带有工作重置按钮的版本。

null

const totalizer = {
    id: 'totalizer',
    beforeUpdate: chart => {
        let totals = {}
        let utmost = 0

            chart.data.datasets.forEach((dataset, datasetIndex) => {
                if (chart.isDatasetVisible(datasetIndex)) {
                    utmost = datasetIndex
                        dataset.data.forEach((value, index) => {
                            totals[index] = (totals[index] || 0) + value
                        })
                }
            })
            chart.$totalizer = {
            totals: totals,
            utmost: utmost
        }
    }
}

const chart = new Chart('chart', {
  type: 'horizontalBar',
  data: {
    labels: ['Brut', 'Net imposable', 'Net'],
    datasets: [{"data":[10,20,10],"label":"1st Presentation \/ Meeting","backgroundColor":"#7B68EE"},{"data":[109,82,22],"label":"Hold\/Uncategorized","backgroundColor":"#B0C4DE"},{"data":[4,14,1],"label":"SGL","backgroundColor":"#F4A460"},{"data":[1,0,0],"label":"PGL","backgroundColor":"#BC8F8F"},{"data":[1,8,1],"label":"QO under evaluation","backgroundColor":"#2E8B57"},{"data":[38,37,16],"label":"Follow-On Meetings","backgroundColor":"#6495ED"},{"data":[9,6,0],"label":"MGL","backgroundColor":"#FFA500"},{"data":[6,32,0],"label":"Identified Opportunities","backgroundColor":"#6B8E23"},{"data":[0,2,0],"label":"RGL","backgroundColor":"#DEB887"}],"yearly":[{"data":[2],"label":"RGL","backgroundColor":"#DEB887"},{"data":[40],"label":"1st Presentation \/ Meeting","backgroundColor":"#7B68EE"},{"data":[10],"label":"QO under evaluation","backgroundColor":"#2E8B57"},{"data":[1],"label":"PGL","backgroundColor":"#BC8F8F"},{"data":[38],"label":"Identified Opportunities","backgroundColor":"#6B8E23"},{"data":[19],"label":"SGL","backgroundColor":"#F4A460"},{"data":[213],"label":"Hold\/Uncategorized","backgroundColor":"#B0C4DE"},{"data":[15],"label":"MGL","backgroundColor":"#FFA500"},{"data":[91],"label":"Follow-On Meetings","backgroundColor":"#6495ED"}],"user":[{"data":[0,1,0,0,2,14,7,0,1,2,0,2,1,4,0,1,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"Identified Opportunities","backgroundColor":"#6B8E23"},{"data":[5,2,0,9,3,0,2,6,5,0,3,0,0,0,2,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0],"label":"1st Presentation \/ Meeting","backgroundColor":"#7B68EE"},{"data":[149,2,39,0,11,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],"label":"Hold\/Uncategorized","backgroundColor":"#B0C4DE"},{"data":[0,2,0,2,0,0,6,4,1,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"SGL","backgroundColor":"#F4A460"},{"data":[2,1,0,0,4,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],"label":"QO under evaluation","backgroundColor":"#2E8B57"},{"data":[7,42,0,21,8,0,5,1,0,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"Follow-On Meetings","backgroundColor":"#6495ED"},{"data":[0,3,0,6,0,0,1,0,0,2,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"label":"MGL","backgroundColor":"#FFA500"},{"data":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"PGL","backgroundColor":"#BC8F8F"},{"data":[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"RGL","backgroundColor":"#DEB887"}]},"filter":{"weekly":["Week 1","Week 2","Week 3","Week 4"]
  },
  options: {
    scales: {
      xAxes: [{
        stacked: true
       
      }],
      yAxes: [{
        stacked: true
      }]
    },
    legend: {
       onClick: 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();
        },
    display: true,
    position: "right",
    labels: {
		filter: function(item, chart) {
          // Logic to remove a particular legend item goes here
          return !item.text.includes('Total');
        },
      fontColor: "black",
      boxWidth: 12,
      fontFamily: "Raleway-medium"
    }
  },
    plugins: {
      datalabels: {
        formatter: (value, ctx) => {
          const total = ctx.chart.$totalizer.totals[ctx.dataIndex]
          return total.toLocaleString('fr-FR', {
             style: 'currency',
            currency: 'EUR'
          })
        },
        align: 'end',
        anchor: 'end',
        display: function(ctx) {
          return ctx.datasetIndex === ctx.chart.$totalizer.utmost
        }
      }
    }
  },
  plugins: [totalizer]
});

$('.reset').click(function(){
  chart.data.datasets.forEach(function(e, i) {
    let meta = chart.getDatasetMeta(i);
    if (meta.hidden) {
      meta.hidden = null;
    }
  });
  chart.update();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>

<button class='reset'>Reset</button>
<canvas id="chart" width="100" height="50"></canvas>

匿名用户

我喜欢@塔哈的解决方案! 你甚至可以把它缩短到

$('.reset').click(function(){
  chart.data.datasets.forEach(e=>e._meta[0].hidden = null);
  chart.update();
});

null

const totalizer = {
    id: 'totalizer',
    beforeUpdate: chart => {
        let totals = {}
        let utmost = 0

            chart.data.datasets.forEach((dataset, datasetIndex) => {
                if (chart.isDatasetVisible(datasetIndex)) {
                    utmost = datasetIndex
                        dataset.data.forEach((value, index) => {
                            totals[index] = (totals[index] || 0) + value
                        })
                }
            })
            chart.$totalizer = {
            totals: totals,
            utmost: utmost
        }
    }
}

const chart = new Chart('chart', {
  type: 'horizontalBar',
  data: {
    labels: ['Brut', 'Net imposable', 'Net'],
    datasets: [{"data":[10,20,10],"label":"1st Presentation \/ Meeting","backgroundColor":"#7B68EE"},{"data":[109,82,22],"label":"Hold\/Uncategorized","backgroundColor":"#B0C4DE"},{"data":[4,14,1],"label":"SGL","backgroundColor":"#F4A460"},{"data":[1,0,0],"label":"PGL","backgroundColor":"#BC8F8F"},{"data":[1,8,1],"label":"QO under evaluation","backgroundColor":"#2E8B57"},{"data":[38,37,16],"label":"Follow-On Meetings","backgroundColor":"#6495ED"},{"data":[9,6,0],"label":"MGL","backgroundColor":"#FFA500"},{"data":[6,32,0],"label":"Identified Opportunities","backgroundColor":"#6B8E23"},{"data":[0,2,0],"label":"RGL","backgroundColor":"#DEB887"}],"yearly":[{"data":[2],"label":"RGL","backgroundColor":"#DEB887"},{"data":[40],"label":"1st Presentation \/ Meeting","backgroundColor":"#7B68EE"},{"data":[10],"label":"QO under evaluation","backgroundColor":"#2E8B57"},{"data":[1],"label":"PGL","backgroundColor":"#BC8F8F"},{"data":[38],"label":"Identified Opportunities","backgroundColor":"#6B8E23"},{"data":[19],"label":"SGL","backgroundColor":"#F4A460"},{"data":[213],"label":"Hold\/Uncategorized","backgroundColor":"#B0C4DE"},{"data":[15],"label":"MGL","backgroundColor":"#FFA500"},{"data":[91],"label":"Follow-On Meetings","backgroundColor":"#6495ED"}],"user":[{"data":[0,1,0,0,2,14,7,0,1,2,0,2,1,4,0,1,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"Identified Opportunities","backgroundColor":"#6B8E23"},{"data":[5,2,0,9,3,0,2,6,5,0,3,0,0,0,2,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0],"label":"1st Presentation \/ Meeting","backgroundColor":"#7B68EE"},{"data":[149,2,39,0,11,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],"label":"Hold\/Uncategorized","backgroundColor":"#B0C4DE"},{"data":[0,2,0,2,0,0,6,4,1,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"SGL","backgroundColor":"#F4A460"},{"data":[2,1,0,0,4,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],"label":"QO under evaluation","backgroundColor":"#2E8B57"},{"data":[7,42,0,21,8,0,5,1,0,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"Follow-On Meetings","backgroundColor":"#6495ED"},{"data":[0,3,0,6,0,0,1,0,0,2,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"label":"MGL","backgroundColor":"#FFA500"},{"data":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"PGL","backgroundColor":"#BC8F8F"},{"data":[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"label":"RGL","backgroundColor":"#DEB887"}]},"filter":{"weekly":["Week 1","Week 2","Week 3","Week 4"]
  },
  options: {
    scales: {
      xAxes: [{
        stacked: true
       
      }],
      yAxes: [{
        stacked: true
      }]
    },
    legend: {
       onClick: 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();
        },
    display: true,
    position: "right",
    labels: {
		filter: function(item, chart) {
          // Logic to remove a particular legend item goes here
          return !item.text.includes('Total');
        },
      fontColor: "black",
      boxWidth: 12,
      fontFamily: "Raleway-medium"
    }
  },
    plugins: {
      datalabels: {
        formatter: (value, ctx) => {
          const total = ctx.chart.$totalizer.totals[ctx.dataIndex]
          return total.toLocaleString('fr-FR', {
             style: 'currency',
            currency: 'EUR'
          })
        },
        align: 'end',
        anchor: 'end',
        display: function(ctx) {
          return ctx.datasetIndex === ctx.chart.$totalizer.utmost
        }
      }
    }
  },
  plugins: [totalizer]
});

$('.reset').click(function(){
  chart.data.datasets.forEach(e=>e._meta[0].hidden = null);
  chart.update();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>

<button class='reset'>Reset</button>
<canvas id="chart" width="100" height="50"></canvas>