如何为小屏幕隐藏Chart.js数据标签

时间:2019-03-05 22:03:50

标签: chart.js

我正在尝试为小屏幕隐藏data labels plugin生成的数据标签。

我认为我可以使用chartjs的onResize属性,并在宽度变小时将display设置为false。这很像here中的隐藏标签解决方案。

不幸的是,我无法使它正常工作。我的以下CodePen无效。

var moneyFormat = wNumb({
    decimals: 0,
    thousand: ',',
    prefix: '$',
    negativeBefore: '-'
});

var percentFormat = wNumb({
    decimals: 0,
    suffix: '%',
    negativeBefore: '-'
});

/*
 * Unregister chartjs-plugins-datalabels - not really necessary for this use case
 */
Chart.plugins.unregister(ChartDataLabels);

var doughnutdata = {
    labels: ['Housing',
        'Food',
        'Transportation',
        'Clothing',
        'Healthcare',
        'Childcare',
        'Misc'],
    datasets: [
        {
            backgroundColor: [
                '#9B2A00',
                '#5B5C90',
                '#6B8294',
                '#1A6300',
                '#BE0000',
                '#B8A853',
                '#64A856'
            ],
            borderColor: [
                '#FFFFFF',
                '#FFFFFF',
                '#FFFFFF',
                '#FFFFFF',
                '#FFFFFF',
                '#FFFFFF',
                '#FFFFFF'
            ],
            data: [88480, 57680, 40050, 18430, 23860, 25840, 17490]
        }
    ]
};

var chartOptions = {
    responsive: true,
    maintainAspectRatio: true,
    legend: {
        labels: {
            boxWidth: 20
        }
    },
    tooltips: {
        callbacks: {
            label: function (tooltipItem, data) {
                var index = tooltipItem.index;
                return data.labels[index] + ': ' + moneyFormat.to(data.datasets[0].data[index]) + '';
            }
        }
    },
    plugins: {
        datalabels: {
            anchor: 'end',
            backgroundColor: function (context) {
                return context.dataset.backgroundColor;
            },
            borderColor: 'white',
            borderRadius: 25,
            borderWidth: 1,
            color: 'white',
            font: {
                size: 10
            },
            formatter: function (value, pieID) {
                var sum = 0;
                var dataArr = pieID.chart.data.datasets[0].data;
                dataArr.map(function (data) {
                    sum += data;
                });
                var percentage = percentFormat.to((value * 100 / sum));
                return percentage;
            }
        }
    }
};

var doughnutID = document.getElementById('doughnutchart').getContext('2d');

var pieChart = new Chart(doughnutID, {
    plugins: [ChartDataLabels],
    type: 'doughnut',
    data: doughnutdata,
    options: chartOptions,
    onResize: function(chart, size) {
        var showLabels = (size.width < 500) ? false : true;
        chart.options = {
            plugins: {
                datalabels: {
                    display: showLabels
                }
            }
        };
    }
});

任何关于我在做错事情(和修复问题)的想法都将不胜感激。

2 个答案:

答案 0 :(得分:0)

和往常一样,一旦我发布问题,我就会给出答案。以下CodePen提供了一种使用嵌入式插件定义的解决方案。如果将浏览器置于开发人员模式并将窗口缩小到小于540像素,则数据标签将消失。

代码如下所示:

"use strict";
/* global Chart */
/* global wNumb */
/* global ChartDataLabels */
/*
 * Unregister chartjs-plugins-datalabels - not really necessary for this use case
 */
Chart.plugins.unregister(ChartDataLabels);

var moneyFormat = wNumb({
  decimals: 0,
  thousand: ",",
  prefix: "$",
  negativeBefore: "-"
});

var percentFormat = wNumb({
  decimals: 0,
  suffix: "%",
  negativeBefore: "-"
});

var doughnutdata = {
  labels: [
    "Housing",
    "Food",
    "Transportation",
    "Clothing",
    "Healthcare",
    "Childcare",
    "Misc"
  ],
  datasets: [
    {
      backgroundColor: [
        "#9B2A00",
        "#5B5C90",
        "#6B8294",
        "#1A6300",
        "#BE0000",
        "#B8A853",
        "#64A856"
      ],
      borderColor: [
        "#FFFFFF",
        "#FFFFFF",
        "#FFFFFF",
        "#FFFFFF",
        "#FFFFFF",
        "#FFFFFF",
        "#FFFFFF"
      ],
      data: [88480, 57680, 40050, 18430, 23860, 25840, 17490]
    }
  ]
};

var chartOptions = {
  responsive: true,
  maintainAspectRatio: true,
  legend: {
    labels: {
      boxWidth: 20
    }
  },
  tooltips: {
    callbacks: {
      label: function(tooltipItem, data) {
        var index = tooltipItem.index;
        return (
          data.labels[index] +
          ": " +
          moneyFormat.to(data.datasets[0].data[index]) +
          ""
        );
      }
    }
  },
  plugins: {
    datalabels: {
      anchor: "end",
      backgroundColor: function(context) {
        return context.dataset.backgroundColor;
      },
      borderColor: "white",
      borderRadius: 25,
      borderWidth: 1,
      color: "white",
      font: {
        size: 10
      },
      formatter: function(value, pieID) {
        var sum = 0;
        var dataArr = pieID.chart.data.datasets[0].data;
        dataArr.map(function(data) {
          sum += data;
        });
        var percentage = percentFormat.to(value * 100 / sum);
        return percentage;
      }
    }
  }
};

var doughnutID = document.getElementById("doughnutchart").getContext("2d");

var pieChart = new Chart(doughnutID, {
  plugins: [
    ChartDataLabels,
    {
      beforeLayout: function(chart) {
        var showLabels = (chart.width) > 500 ? true : false;
        chart.options.plugins.datalabels.display = showLabels;
      }
    },
    {
      onresize: function(chart) {
        var showLabels = (chart.width) > 500 ? true : false;
        chart.options.plugins.datalabels.display = showLabels;
      }
    }
  ],
  type: "doughnut",
  data: doughnutdata,
  options: chartOptions
});

我希望这是有用的。

答案 1 :(得分:0)

可以使用scriptable options来实现响应能力,在您的情况下,您可以为display选项使用一个函数,当图表小于特定大小时,该函数返回false({{ 3}}):

options: {
  plugins: {
    datalabels: {
      display: function(context) {
        return context.chart.width > 500;
      }
    }
  }
}