如何在刻度标签之间添加填充?

时间:2017-10-02 18:25:17

标签: javascript chart.js

如何在图表标签之间添加填充。我需要总是显示刻度标签,但如何在刻度标签之间添加间距?

另一种可能的解决方案是使图表的高度更高。仅当将图表缩小到浏览器大小以使宽度小于320px时才会发生这种情况。

image of overlapping labels

这是小提琴:https://jsfiddle.net/leetcat/4d7juow3/

在我的情况下,标签是“健康”,“反应”,“受伤”,“生病”。

我试过了:

options: {
  layout: {
      padding: {
        top: 20
      }
    }
}

scales: { 
  yAxes: [{   
    ticks: {
      padding: 10
    }
  }]
}

1 个答案:

答案 0 :(得分:1)

您可以将maintainAspectRatio: false添加到图表选项中,并在图表元素上设置最小高度。

var ctx = document.getElementById("myChart");

var data = {
  labels: ["2017-09-26T00:00:00Z", "2017-09-27T00:00:00Z", "2017-09-28T00:00:00Z", "2017-09-29T00:00:00Z", "2017-09-30T00:00:00Z", "2017-10-01T00:00:00Z", "2017-10-02T00:00:00Z"],
  datasets: [{
    label: "Self Rating",
    backgroundColor: '#777777',
    borderColor: '#777777',
    data: [1, 2, 0, 0, 0, 0, 0],
    fill: false,
    yAxisID: "y-axis-1",
  }]
};

var myChart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    responsive: true,
    maintainAspectRatio: false,
    legend: {
      position: 'bottom',
    },
    title: {
      display: true,
      text: 'Check-In History',
    },
    scales: {
      // Need to limit tick marks to be days
      xAxes: [{
        display: true,
        type: 'time',
        time: {
          unit: 'day',
          unitStepSize: 1,
          displayFormats: {
            'day': 'MMM DD'
          }
        }
      }],
      yAxes: [{
        id: "y-axis-1",
        display: true,
        position: "left",
        scaleLabel: {
          display: true,
          labelString: 'Mental Health Continuum'
        },
        ticks: {
          min: 0,
          max: 3.05,
          stepSize: 1,
          suggestedMin: 0,
          suggestedMax: 3.05,
          callback: function(label, index, labels) {
            switch (label) {
              case 0:
                return 'Ill';
              case 1:
                return 'Injured';
              case 2:
                return 'Reacting';
              case 3:
                return 'Healthy';
            }
          }
        },
        gridLines: {
          display: false
        }
      }]
    }
  }
});
#myChart {
  min-height: 350px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>

<div id="wrapper">
  <canvas id="myChart"></canvas>
</div>

相关问题