向空Chart.js图表​​添加新数据不会正确呈现新数据

时间:2014-08-22 21:13:36

标签: javascript html5 canvas charts chart.js

我有一个Chart.js条形图,可以在页面加载时实例化。然后,我希望在图表可用时将数据添加到图表中(创建时没有可用的数据)。但是,传递新数据似乎总是使图表无法呈现传入的第一组数据:

var bar_chart_data = {
labels: [],
datasets: [
    {
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.5)",
        strokeColor: "rgba(220,220,220,0.8)",
        highlightFill: "rgba(220,220,220,0.75)",
        highlightStroke: "rgba(220,220,220,1)",
        data: []
    }
]
};

var ctx = $("#bar-chart").get(0).getContext("2d");
var bar_chart = new Chart(ctx).Bar(bar_chart_data);

bar_chart.addData([2], "test")
bar_chart.addData([2], "test2")

我尝试过各种各样的事情,包括:

  • 传入空标签和数据数组(上图)
  • 传入空标签数组,没有设置数据字段
  • 使用一个元素传入有效的标签和数据数组,然后使用bar_chart.removeData()删除它,然后再次尝试添加有效数据
  • 在添加新数据后调用bar_chart.update()

jsfiddle

1 个答案:

答案 0 :(得分:1)

当图表试图计算X而图表中没有数据时,问题出在比例类内。当没有数据存在时会导致无穷大,这会弄乱图表。所以你可以像这样重写Chart.Scale.calculateX:(http://jsfiddle.net/leighking2/3nrhtyz4/) 编辑 - @Matt Humphrey指出修复不适用于Line图,所以这是基于他的github评论的更新(github.com/nnnick/Chart.js/issues/573#issuecomment-56102121)

   Chart.Scale = Chart.Scale.extend({
    calculateX: function (index) {
        //check to ensure data is in chart otherwise we will get inifinity
        if (!(this.valuesCount - (this.offsetGridLines ? 0 : 1))) {
            return 0;
        }
        var isRotated = (this.xLabelRotation > 0),
            // innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding,
            innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight),
            valueWidth = this.valuesCount === 0 ? 0 : innerWidth / (this.valuesCount - ((this.offsetGridLines) ? 0 : 1)),
            valueOffset = (valueWidth * index) + this.xScalePaddingLeft;

        if (this.offsetGridLines) {
            valueOffset += (valueWidth / 2);
        }

        return Math.round(valueOffset);
    },
});

您现在可以像以前一样正常使用图表js。

var bar_chart_data = {
    labels: [],
    datasets: [{
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.5)",
        strokeColor: "rgba(220,220,220,0.8)",
        highlightFill: "rgba(220,220,220,0.75)",
        highlightStroke: "rgba(220,220,220,1)",
        data: []
    }, {
        label: "My Second dataset",
        fillColor: "rgba(151,187,205,0.5)",
        strokeColor: "rgba(151,187,205,0.8)",
        highlightFill: "rgba(151,187,205,0.75)",
        highlightStroke: "rgba(151,187,205,1)",
        data: []
    }]
};

var bar_chart_options = {
    responsive: false
};

var ctx = $("#bar-chart").get(0).getContext("2d");
var bar_chart = new Chart(ctx).Bar(bar_chart_data, bar_chart_options);

bar_chart.addData([1, 1], "test")
bar_chart.addData([2, 2], "test2")