本文介绍了如何从数组创建morris.js图表​​?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从数组中获取数据以正确显示在morris.js图表中时遇到问题.

I am having an issue getting data from array to show correctly in a morris.js chart.

从此代码段中可以看到,只有最后一个对象在图表上输出:

As you can see from this snippet only the last object is output on chart:

示例:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

var dates = ['2015-01','2016-01','2016-03'];
var valueA = ['10','30','60'];
var valueB = ['100','50','70'];

var z=0;

for (tot=dates.length; z < tot; z++) {
  var myArray = [{'d': dates[z], 'a': valueA[z], 'b': valueB[z]}];
}

Morris.Bar({
    element: 'morris-bar-chart',
    data: myArray,
    xkey: 'd',
    ykeys: ['a', 'b'],
    labels: ['2014', '2015'],
    xLabelFormat: function (x) { // <-- changed
        console.log("this is the new object:" + x);
        var month = months[x.x];
        return month;
    },
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://cdn.oesmith.co.uk/morris-0.4.3.min.css" rel="stylesheet" />
<script src="http://cdn.oesmith.co.uk/morris-0.5.0.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>

<div id="morris-bar-chart" style="height: 250px;"></div>

我的名为myArray的数组在for循环中有3个对象,那么为什么morris.js仅输出图表中的最后一个对象?

My array called myArray has 3 objects in a for loop, so why morris.js output only the last one in chart?

推荐答案

请尝试以下操作:

//......
var myArray = [];
for (tot=dates.length; z < tot; z++) {
   myArray.push({'d': dates[z], 'a': valueA[z], 'b': valueB[z]});
}
//......
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

var dates = ['2015-01','2016-01','2016-03'];
var valueA = ['10','30','60'];
var valueB = ['100','50','70'];

var z=0;
var myArray = [];

for (tot=dates.length; z < tot; z++) {
   myArray.push({'d': dates[z], 'a': valueA[z], 'b': valueB[z]});
}

Morris.Bar({
    element: 'morris-bar-chart',
    data: myArray,
    xkey: 'd',
    ykeys: ['a', 'b'],
    labels: ['2014', '2015'],
    xLabelFormat: function (x) { // <-- changed
        console.log("this is the new object:" + x);
        var month = months[x.x];
        return month;
    },
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://cdn.oesmith.co.uk/morris-0.4.3.min.css" rel="stylesheet" />
<script src="http://cdn.oesmith.co.uk/morris-0.5.0.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>

<div id="morris-bar-chart" style="height: 250px;"></div>

这篇关于如何从数组创建morris.js图表​​?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 04:34