【问题标题】:Chart.js - mixing bar and line graphs - can I get the lines to fill the full column?Chart.js - 混合条形图和折线图 - 我可以让线条填充整列吗?
【发布时间】:2018-05-24 16:38:55
【问题描述】:

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

请注意,有时条形图会越过红色虚线。有时红色虚线会在不同的位置(通常在 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 是否有使红色虚线延伸到整个列宽的选项或方法?

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

【问题讨论】:

    标签: javascript chart.js


    【解决方案1】:

    不幸的是,没有办法“配置”图表来实现您想要的。这一切都与折线图比例绘图的工作方式有关。话虽如此,您仍然可以通过使用一些“虚拟”数据欺骗chart.js 来实现此行为。

    基本上,您创建一个“虚拟”第一个和最后一个标签。然后将相应的“虚拟”第一个和最后一个值添加到您的条形数据数组(永远不会显示此数据)。然后将相应的“虚拟”第一个和最后一个值添加到您的行数据数组中,但请确保您将值设置为与下一个/上一个值相同以结束一条直线(否则您的线将在开始和结束处倾斜)。这就是我的意思。

    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 以了解它的实际效果。

    【讨论】:

    • 赏金即将送达您。谢谢老哥
    • 我不得不使用null 而不是0 作为虚拟数据点。使用零时,第一个虚拟条仍然出现在左侧。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    相关资源
    最近更新 更多