当Chart.js中未显示数据时隐藏Y轴标签

lnxxn5zx  于 2022-11-07  发布在  Chart.js
关注(0)|答案(4)|浏览(267)

我有一个Chart.js条形图,其中显示了两组数据:总SQL查询和慢速SQL查询。我有Y轴标签的每一个相应的数据集。图形可以看到如下:

当我将其中一组数据切换为不显示时,对应的Y轴标签仍会显示。在解释图形时,这有点令人困惑。如下图所示:

**我的问题:**如何隐藏当前未显示的任何数据集的Y轴标签?

以下是我目前设置图表的方式:

<canvas id="SQLPerformanceChart" minHeight="400"></canvas>
<script type="text/javascript">
    ...
    var data = {
        labels: labelArray,
        datasets: [{
            label: "Total SQL Queries",
            fill: false,
            borderWidth: 1,
            borderColor: "green",
            backgroundColor: "rgba(0, 255, 0, 0.3)",
            yAxisID: "y-axis-0",
            data: totalQueriesArray
        }, {
            label: "Slow SQL Queries",
            fill: false,
            borderWidth: 1,
            borderColor: "orange",
            backgroundColor: "rgba(255, 255, 0, 0.3)",
            yAxisID: "y-axis-1",
            data: slowQueriesArray,
        }]
    };

    var options = {
        animation: false,
        scales: {
            yAxes: [{
                position: "left",
                ticks: {
                    beginAtZero: true
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Total SQL Queries'
                },
                id: "y-axis-0"
            }, {
                position: "right",
                ticks: {
                    beginAtZero: true
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Slow SQL Queries'
                },
                id: "y-axis-1"
            }]
        },
        tooltips: {
            enabled: true,
            mode: 'single',
            callbacks: {
                title: function(tooltipItem, data) {
                    return data.label;
                },
                beforeLabel: function(tooltipItem, data) {
                    if (tooltipItem.index == 24) {
                        return data.labels[tooltipItem.index] + " - Now";
                    } else {
                        return data.labels[tooltipItem.index] + " - " + data.labels[(tooltipItem.index) + 1];
                    }
                }
            }
        }
    }

    var ctx = document.getElementById("SQLPerformanceChart");
    var SQLPerformanceChart = new Chart(ctx, {
        type: 'bar',
        data: data,
        options: options
    });
</script>
gblwokeq

gblwokeq1#

您可以将回调函数添加到图例onClick:

var options = {
        animation: false,
        scales: {
            yAxes: [{
                position: "left",
                ticks: {
                    beginAtZero: true
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Total SQL Queries'
                },
                id: "y-axis-0"
            }, {
                position: "right",
                ticks: {
                    beginAtZero: true
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Slow SQL Queries'
                },
                id: "y-axis-1"
            }]
        },
        legend: {
        onClick: function(event, legendItem) {
            //get the index of the clicked legend
            var index = legendItem.datasetIndex;
            //toggle chosen dataset's visibility
            SQLPerformanceChart.data.datasets[index].hidden = 
                !SQLPerformanceChart.data.datasets[index].hidden;
            //toggle the related labels' visibility
            SQLPerformanceChart.options.scales.yAxes[index].display =                 
                !SQLPerformanceChart.options.scales.yAxes[index].display;
            SQLPerformanceChart.update();
        }
        }
    }
kuarbcqp

kuarbcqp2#

此解决方案适用于使用angular-chartjs,以及将此行为应用于所有显示的图表的情况。
如果要跳到代码,请选中此fiddlejs
您也可以选中其他fiddlejs,以检查默认Angular 图表行为。

循序渐进:

我在angular-chart.js中使用了第一个图表示例,因此这将是单击后的最终结果:

<div ng-app="app" ng-controller="MainController as mainCtrl">  
        <canvas id="line" class="chart chart-line" chart-data="data"
        chart-labels="labels" chart-series="series" chart-options="options"
        chart-dataset-override="datasetOverride" chart-click="onClick">
      </canvas>
    </div>

1.替换全局图表的处理程序:

Chart.defaults.global.legend.onClick = function (e, legendItem) {
  var idx = legendItem.datasetIndex;

  // IMPORTANT charts will be created in the second and third step
  var chart = charts[e.srcElement.id];
  chart.options.scales.yAxes[idx].display = !chart.options.scales.yAxes[idx].display;

  var meta = chart.getDatasetMeta(idx);
  // See controller.isDatasetVisible comment
  meta.hidden = meta.hidden === null ? !chart.data.datasets[idx].hidden : null;

  chart.update();

};

1.创建一个全局变量charts,这样我们就可以访问画布ID为的每个图表:

var charts = {};

1.使用chart-create事件填充图表变量:

angular.module("app", ["chart.js"]).controller("MainController", function ($scope) {
  $scope.$on('chart-create', function (event, chart) {
    charts[chart.chart.canvas.id] = chart;
  });

  $scope.labels = ["January", "February", "March", "April", "May", "June", "July"];
  $scope.series = ['Series A', 'Series B'];
  $scope.data = [...

我希望会有一个更好的方法从画布id获得图表,但据我所知这是suggested way by the developers

uurv41yg

uurv41yg3#

如果您将ng2图表与chart.js和Angular 7^一起使用,并且希望将此行为应用于所有显示的图表,则此解决方案适用。

import Chart from chart.js
    Chart.defaults.global.legend.onClick = function (e: MouseEvent, chartLegendLabelItem: ChartLegendLabelItem) {
  const idx: number = chartLegendLabelItem.datasetIndex;
  const chart = this.chart;
  chart.options.scales.yAxes[idx].display = !chart.options.scales.yAxes[idx].display;

  const meta = chart.getDatasetMeta(idx);
  meta.hidden = meta.hidden === null ? !chart.data.datasets[idx].hidden : null;

  chart.update();

};

或用于本地配置

legend: <ChartLegendOptions>{
         onClick: function (e: MouseEvent, chartLegendLabelItem:ChartLegendLabelItem) {
      const idx: number = chartLegendLabelItem.datasetIndex;
      const chart = this.chart;
      chart.options.scales.yAxes[idx].display = 
     !chart.options.scales.yAxes[idx].display;

      const meta = chart.getDatasetMeta(idx);
      meta.hidden = meta.hidden === null ? 
             !chart.data.datasets[idx].hidden : null;

      chart.update();

    }
}
gcmastyq

gcmastyq4#

我在使用v3.8.0时沿着这个问题,上面的任何一个都不适合我。这段代码适合我。注意,我将所有图表示例存储在一个Map中,因为我在同一页上有多个图表。

var instances = new Map();

当我创造incances时,我把它们放在那里。
现在,隐藏Y轴标签和图例上的数据单击:

onClick: function (event, legendItem) {
                            var instance = instances.get(event.chart.id);
                            var meta = instance.getDatasetMeta(legendItem.datasetIndex);
                            var newValue = !meta.yScale.options.display;
                            meta.hidden = meta.yScale.options.display;
                            meta.yScale.options.display = newValue;
                            instance.update();
                        }

相关问题