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

时间:2016-10-12 19:37:56

标签: javascript chart.js

我有一个Chart.js条形图,显示两组数据:Total SQL Queries和Slow SQL Queries。我为每组数据都有Y轴标签。该图表如下所示:

SQL Performance graph

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

enter image description here

我的问题:如何隐藏当前未显示的任何数据集的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>

3 个答案:

答案 0 :(得分:5)

您可以在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();
        }
        }
    }

答案 1 :(得分:1)

如果您将ng2-charts与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();

    }
}

答案 2 :(得分:0)

如果您使用angular-chartjs ,并且要将此行为应用于所有显示的图表,则适用此解决方案。

如果要跳至代码,请选中此fiddlejs

您还可以检查其他fiddlejs来检查默认的Angular-Chartjs 行为。


逐步:

我使用first chart example in angular-chart.js,因此这是单击后的最终结果:

enter image description here

    <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