снимите отметку с легенды при нажатии кнопки - PullRequest
1 голос
/ 16 июня 2020

Я создал диаграмму с диаграммой. js и у меня есть событие onclick для легенды. Я хочу показать всю легенду без зачеркивания

 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>

невозможно показать легенду, все выбранные при нажатии кнопки

Ответы [ 2 ]

2 голосов
/ 16 июня 2020

Вот версия с работающей кнопкой сброса легенды.

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, i) => {
    chart.getDatasetMeta(i).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>
1 голос
/ 16 июня 2020

Мне нравится решение @Taha! Вы даже можете сократить его до

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

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...