How to create a morris.js chart from array?

这一生的挚爱 提交于 2019-12-11 06:35:32

问题


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:

Example:

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>

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


回答1:


Please try this:

//......
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>


来源:https://stackoverflow.com/questions/38411239/how-to-create-a-morris-js-chart-from-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!