Chart.js - 混合条形图和折线图 - 我可以获得填充整列的线条吗?

时间:2017-03-24 16:58:35

标签: javascript chart.js

我正在使用Chart.js v2.5.0来创建这样的图表:

enter image description here

请注意,有时条形图会越过红色虚线。有时红色虚线将处于不同的位置(通常为25,但在某些月份将处于其他水平)。

我的问题是我希望红色虚线延伸到列的整个宽度。正如您在第一列中看到的那样,红色虚线仅进入色谱柱的一半。我在图表的另一端有同样的问题,红色虚线只进入了列的一半。

我目前的实现是混合图表,一个是条形图,另一个是折线图 - 数据如下:

    data = {
        labels: ['Jan 21st', 'Feb 21st', 'Mar 21st', 'Apr 21st']
        datasets: [
            {
                type: 'bar',
                label: 'A',
                data: [10, 25, 18, 37],
            },
            {
                type: 'line',
                label: 'B',
                data: [25, 25, 25, 25],
                fill: false,
                borderWidth: 1,
                borderColor: '#f00',
                borderDash: [5,4],
                lineTension: 0,
                steppedLine: true
            }
        ]
    }

Chart.js是否有选项或方法使红色虚线延伸到整列宽度?

我有另一个想法,但我不确定这是否可行:我可以使用红色虚线条形图,只显示条形图的顶行吗?

1 个答案:

答案 0 :(得分:7)

不幸的是,没有办法配置"图表实现你想要的。这一切都与折线图缩放图的工作方式有关。话虽如此,你仍然可以通过欺骗 chart.js使用一些" dummy"来实现这种行为。数据。

基本上,你创建一个"虚拟"第一个和最后一个标签然后添加一个相应的"虚拟"条形数据数组的第一个和最后一个值(此数据永远不会显示)。然后添加一个相应的"虚拟"行数据数组的第一个和最后一个值,但请确保将值设置为与下一个/ prev值相同,最后得到一条直线(否则您的行将在开头和结尾处成角度)。这就是我的意思。

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['dummy1', 'Jan 21st', 'Feb 21st', 'Mar 21st', 'Apr 21st', 'dummy2'],
    datasets: [
      {
        type: 'bar',
        label: 'A',
        // the 1st and last value are placeholders and never get displayed on the chart
        data: [0, 10, 25, 18, 37, 0],
      },
      {
        type: 'line', 
        label: 'B',
        // the 1st and last value are placeholders and never get displayed on the chart
        // to get a straight line, the 1st and last values must match the same value as
        // the next/prev respectively
        data: [25, 25, 25, 25, 25, 25],
        fill: false,
        borderWidth: 1,
        borderColor: '#f00',
        borderDash: [5,4],
        lineTension: 0,
        steppedLine: true
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],  
      xAxes: [{
        // exclude the 1st and last label placeholders by specifying the min/mix ticks
        ticks: {
          min: 'Jan 21st',
          max: 'Apr 21st',
        }
      }],
    }
  }
});

结帐codepen example以查看其实际效果。