如何创建垂直轴(Y轴)为字符串的图形?

2022-02-24 00:00:00 javascript chart.js

我要使用Chart.js制作的图形是一个垂直轴上有字符串、水平轴上有数字的折线图。 例如,横轴是时间,垂直轴是帽子的颜色。 请参见下图

var myChart = new Chart(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],//Number of frames
    datasets: [{
      label: 'The colour of the hat of the person in the frame',
      data: ["red","blue","red","blue","yeallow","red","blue","red","blue","yeallow",.....],
      borderColor: '#f88',
    }],
  }
});


解决方案

是,您必须将y刻度设置为CATEGORY,并为其提供标签数组,然后您可以在数据数组中提及这些标签:

const options = {
  type: 'line',
  data: {
    labels: [1, 2, 3, 4, 5, 6],
    datasets: [{
      label: '# of Points',
      data: ["Blue", "Red", "Red", "Orange", "Green", "Orange"],
      borderColor: 'pink'
    }]
  },
  options: {
    scales: {
      y: {
        type: 'category',
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
      },
    }
  }
}

const 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/3.7.0/chart.js"></script>
</body>

相关文章