0

有谁知道这是否可能?基本上我希望图表有标签,例如 [Jan, Feb, March],我希望能够打开和关闭这些值。看起来很简单,但事实证明是有问题的。

4

1 回答 1

0

dataset您可以为每个条创建单独的并定义data入点格式,如下所示:

data: [{ x: 1, y: 16 }]

此外,您需要定义将包含标签的第二个 x 轴。

{
  offset: true,
  gridLines: {
    display: false
  }
}

labels每次 a 的状态发生变化时,都需要以编程方式收集和定义第二个 x轴上hiddendataset。这可以通过插件核心 API来完成。API 提供了不同的钩子,可用于执行自定义代码。在你的情况下,你可以使用beforeLayout钩子。

plugins: [{
  beforeLayout: chart => chart.chart.options.scales.xAxes[1].labels = chart.chart.data.datasets.filter(ds => !ds._meta[0].hidden).map(ds => ds.label)
}]

请看下面的可运行代码,看看它是如何工作的。

new Chart(document.getElementById('chart'), {
  type: 'bar',
  plugins: [{
    beforeLayout: chart => chart.chart.options.scales.xAxes[1].labels = chart.chart.data.datasets.filter(ds => !ds._meta[0].hidden).map(ds => ds.label)
  }],
  data: {
    datasets: [{
        label: 'A',
        data: [{ x: 1, y: 16 }],
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgb(255, 99, 132)',
        borderWidth: 1,
        categoryPercentage: 1
      },
      {
        label: 'B',
        data: [{ x: 2, y: 22 }],
        backgroundColor: 'rgba(255, 159, 64, 0.2)',
        borderColor: 'rgb(255, 159, 64)',
        borderWidth: 1,
        categoryPercentage: 1
      },
      {
        label: 'C',
        data: [{ x: 3, y: 18 }],
        backgroundColor: 'rgba(255, 205, 86, 0.2)',
        borderColor: 'rgb(255, 205, 86)',
        borderWidth: 1,
        categoryPercentage: 1
      },
      {
        label: 'D',
        data: [{ x: 4, y: 13 }],
        backgroundColor: 'rgba(75, 192, 192, 0.2)',
        borderColor: 'rgb(75, 192, 192)',
        borderWidth: 1,
        categoryPercentage: 1
      },
      {
        label: 'E',
        data: [{ x: 5, y: 5 }],
        backgroundColor: 'rgba(54, 162, 235, 0.2)',
        borderColor: 'rgb(54, 162, 235)',
        borderWidth: 1,
        categoryPercentage: 1
      },
      {
        label: 'F',
        data: [{ x: 6, y: 16 }],
        backgroundColor: 'rgba(153, 102, 255, 0.2)',
        borderColor: 'rgb(153, 102, 255)',
        borderWidth: 1,
        categoryPercentage: 1
      },
    ]
  },
  options: {
    tooltips: {
      callbacks: {
        title: () => undefined
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
          display: false
        },
        {
          offset: true,
          gridLines: {
            display: false
          }
        }
      ]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="chart" height="80"></canvas>

于 2021-05-13T13:57:18.887 回答