Chart.js:水平堆积条形图中x轴的最小值

时间:2017-05-10 13:19:28

标签: javascript charts chart.js

我使用Chart.js生成水平堆积条形图。该图表目前看起来像这样: enter image description here

此图表显示用户应在多长时间内恢复房屋的特定组件。我试图将此更改为用户应在哪一年进行恢复。将当前年份添加到值会产生以下结果: enter image description here

如果我可以将x轴的起始值设置为当前年份,那么这就是我所需要的。我尝试这样设置最小值,如下所示:

options: {
    scales: {
        xAxes: [{
            ticks: {
                min: 2017
            },
        ...

不幸地导致完全不显示数据集:

enter image description here

我尝试了添加当前年份并设置最小值的所有组合,但没有任何结果可以生成有用的图表。

在下文中,您可以看到我当前的源代码:

var mainChart_ctx = document.getElementById("main_chart").getContext("2d");

var mainChart_config = {
  type: 'horizontalBar',
  data: {
    labels: ['Kellerdecke', 'Fenster', 'Außenwand', 'Erdberührter Boden', 'Dach'],
    datasets: [{
        label: 'Beginn ab heute',
        backgroundColor: 'transparent',
        data: [4, 21, 25, 25, 25],
        borderColor: '#666',
        borderWidth: 1
      },
      {
        label: 'Sanierungsdauer',
        backgroundColor: '#ffcc00',
        data: [2, 5, 5, 5, 5],
        borderColor: '#666',
        borderWidth: 1
      },
      {
        label: 'Mittlere Restlebensdauer',
        backgroundColor: 'orange',
        data: [39, 0, 38, 51, 37],
        borderColor: '#666',
        borderWidth: 1
      },
      {
        label: 'Maximale Restlebensdauer',
        backgroundColor: 'orangered',
        data: [20, 0, 0, 0, 0],
        borderColor: '#666',
        borderWidth: 1
      }
    ]
  },
  options: {
    tooltips: {
      enabled: true
    },
    legend: {
      display: false
    },
    title: {
      display: true,
      text: 'Sanierungsfahrplan',
      fontSize: 24
    },
    scales: {
      xAxes: [{
        ticks: {
          min: 0 /* Todo: change to current year? */
        },
        stacked: true,
        scaleLabel: {
          display: true,
          labelString: 'Jahre',
          fontSize: 16
        }
      }],
      yAxes: [{
        ticks: {
          stepSize: 10
        },
        stacked: false,
        scaleLabel: {
          display: true,
          labelString: 'Bauteil',
          fontSize: 16
        },
      }]
    }
  }
};

mainChart = new Chart(mainChart_ctx, mainChart_config)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.min.js"></script>

<canvas id="main_chart"></canvas>

2 个答案:

答案 0 :(得分:0)

我能够使用这样的回调获得合适的结果:

xAxes: [{
    ticks: {
        min: 0,
        callback: function (value, index, values) {
            return value + 2017;
        }
     },
...
]

答案 1 :(得分:0)

我发现建议的Min效果很好:

options: {
  scales: {
      xAxes: [{
          display: true,
          ticks: {
              suggestedMin: 2017
          }
      }]
  }
}