【问题标题】:how to show only each 15th x-labels in line chart chart.js in angular 6?如何在角度 6 中仅显示折线图 chart.js 中的每 15 个 x 标签?
【发布时间】:2018-09-02 10:03:49
【问题描述】:

我有一个图表js的折线图,是这样的:

this.canvas = document.getElementById('myChart');
this.ctx = this.canvas.getContext('2d');
let myChart = new Chart(this.ctx, {
  type: 'line',
  data: {
    labels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",],
    datasets: [
      {
        label: '',
        fill: false,
        lineTension: 0.1,
        backgroundColor: "steelblue",
        borderColor: "steelblue",
        borderCapStyle: 'butt',
        borderDash: [],
        borderDashOffset: 0.0,
        borderJoinStyle: 'miter',
        pointBorderColor: "steelblue",
        pointBackgroundColor: "steelblue",
        pointBorderWidth: 1,
        pointHoverRadius: 5,
        pointHoverBackgroundColor: "steelblue",
        pointHoverBorderColor: "steelblue",
        pointHoverBorderWidth: 2,
        pointRadius: 2,
        pointHitRadius: 10,
        data: [40, 59, 46, 50, 56, 52, 40, 58, 29, 46, 36, 36, 45, 31, 19, 24, 26, 12, 30, 32, 31, 42, 37, 50, 34, 39, 28, 26, 33, 21],
      }
    ]
  },
  options: {
    responsive: false,
    scales: {
      xAxes: [{
        gridLines: {
          display: false
        }
      }],
    },
  }
});

}

当我运行它时,它会在 x 轴上显示所有标签。但我只想显示标签1, 15, 30!我曾经将其他标签设置为"",但是这样,工具提示不会显示x轴数据!我现在该怎么办?我还有另一个问题是图表顶部的标签。我在选项中设置了图例:{display: false},但表格将不再显示

【问题讨论】:

标签: javascript label chart.js angular6 linechart


【解决方案1】:

您可以为scales.xAxes 选项定义userCallback 函数...

   xAxes: [{
        ticks: {
            userCallback: function(item, index) {
              if (index===0) return item;
              if (((index+1)%15)===0) return item;
            },
            autoSkip: false
        },
        gridLines: {
          display: false
        }
   }]...

要隐藏“图例”(不是“图例”),请使用:

legend: {
    display: false
}

演示:https://www.codeply.com/go/5QI8eVTPnY

类似:Show only nth tick LINE on x-axis for Chart.js diagram

【讨论】:

  • @themes-guide 图例属性没问题,但是当我使用用户回调函数时,它返回一个错误,指出属性“比例”的类型不兼容!我正在使用 Angular 6,但我不知道有什么问题
  • 我不知道。 “scales”是 chart.js 选项之一,但在您用于 Angular 6 的任何库中,它可能有所不同。无论如何,我已经回答了“如何仅显示每 15 个 x-labels”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多