Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

javascript - How to create two x-axes label using chart.js

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This question has already been answered on github here

Here is a working 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...