如何使用 chart.js 创建两个 x 轴标签

2022-01-22 00:00:00 javascript chart.js

有一种方法可以为 y 轴创建两​​个标签.但是如何在 chart.js 中制作多个 x 轴标签?例如:如图所示的示例:如何对(两级)轴标签进行分组

There is a way to create two label for y-axes. But how do you make a multiple x-axes label in chart.js? eg: example as in this picture: How to group (two-level) axis labels

推荐答案

这个问题已经在github上回答了这里

This question has already been answered on github here

这是一个有效的 JSFiddle

var ctx = $("#c");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["January;2015", "February;2015", "March;2015", "January;2016", "February;2016", "March;2016"],
    datasets: [{
      label: '# of Votes',
      xAxisID:'xAxis1',
      data: [12, 19, 3, 5, 2, 3]
    }]
  },
  options:{
    scales:{
      xAxes:[
        {
          id:'xAxis1',
          type:"category",
          ticks:{
            callback:function(label){
              var month = label.split(";")[0];
              var year = label.split(";")[1];
              return month;
            }
          }
        },
        {
          id:'xAxis2',
          type:"category",
          gridLines: {
            drawOnChartArea: false, // only want the grid lines for one axis to show up
          },
          ticks:{
            callback:function(label){
              var month = label.split(";")[0];
              var year = label.split(";")[1];
              if(month === "February"){
                return year;
              }else{
                return "";
              }
            }
          }
        }],
      yAxes:[{
        ticks:{
          beginAtZero:true
        }
      }]
    }
  }
});

<body>
<canvas id="c" width="400" height="300"></canvas>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
</body>

相关文章