-1

我有一个 chartjs 折线图要求,客户要求仅在有数据点时才在 x 轴上显示标签。请在下面找到他的模型。

在此处输入图像描述

x轴是时间,这就是我得到的。

在此处输入图像描述

我怎样才能做到这一点?

这是我的配置。

    options={{
                scales: {
                    xAxes: [
                        {
                            distribution: 'linear',
                            type: "time",
                            time: {
                                min: range_min.toDateString(),
                                max: range_max.toDateString(),
                                unit: "day",
                                stepSize: "1",
                            },
                            id: 'xAxis',
                            ticks: {
                                autoSkip: true,
                                callback: function (value, index, values) {
                                    return formatDate(new Date(value))
                                },
                            }
                        },
                    ],
                },
                pan: {
                    enabled: true,
                    mode: "x",
                    speed: 1,
                    threshold: 1,
                },
                zoom: {
                    enabled: true,
                    drag: true,
                    sensitivity: 0.5,
                    mode: "x",
                },
                annotation: {
                    annotations: [{
                        type: 'line',
                        mode: 'vertical',
                        scaleID: 'xAxis',
                        value: 1582229218219,
                        endValue: 1582229218219,
                        borderColor: 'rgb(75, 0, 0)',
                        borderWidth: 4
                    }]

                },
                onClick: (event, item) => {
                    console.log(item)
                }

            }}
4

1 回答 1

0

是的,这是可能的,您可以通过使用 tick 回调来实现这一点,如下所示:

const data = [{
  x: 'Red',
  y: 10
}, {
  x: 'Yellow',
  y: 5
}, {
  x: 'Orange',
  y: 3
}]

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data,
      borderWidth: 1,
      backgroundColor: 'red',
      borderColor: 'red',
      fill: false
    }]
  },
  options: {
    scales: {
      xAxes: [{
        ticks: {
          callback: (val, y, z, t) => (
            data.map(el => el.x).indexOf(val) >= 0 ? val : null
          )
        }
      }]
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>

于 2021-04-13T19:44:31.447 回答