javascript - 如何在 Angular 6的折线图chart.js中仅显示每15个x标签?

标签 javascript label chart.js angular6 linechart

我有一个图表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 轴数据!我现在应该怎么做?我还有另一个问题,那就是图表顶部的标签。我在选项中设置了 legends: {display: false} 但表格将不再显示

最佳答案

您可以为 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

关于javascript - 如何在 Angular 6的折线图chart.js中仅显示每15个x标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52135902/

相关文章:

javascript - 如何在 Angular 中滑动时隐藏 div

javascript - Hammer.js jQUery 插件在 IE7/8 中不起作用

javascript - 编译 TypeScript 时忽略类型错误,但不忽略语法错误

java - 使用 FXML 将鼠标单击操作事件添加到 JavaFX 中的标签

python - 标签上的 Tkinter 透明度

javascript - 单击以显示更多 - 也许是 JS?

swift - 在标签上显示可选的双数

javascript - 如何使用 chartjs 将 x 轴值和线点移动到两条 x 轴线的中间?

angularjs - 删除 Angular 图表左侧和右侧的额外空白

reactjs - 数组没有在 useState Hook 中更新?