Search code examples
javascriptmorris.js

how to display month names in string on x-axis in Morris area chart


Morris area chart breaks when string values are added in x-axis and these errors are shown:

Error: attribute d: Expected moveto path command ('M' or 'm'), "Z".

Error: attribute d: Expected number, "M,0,0".

Morris.Area({
  element: 'area-example',
  data: [
    { y: 'Jan', a: 10},
    { y: 'Feb', a: 20},
    { y: 'Mar', a: 30},
    { y: 'Apr', a: 40},
    { y: 'May', a: 50},
    { y: 'Jun', a: 60}       
  ],
  xkey: 'y',
  ykeys: ['a'],
  labels: ['Series A']
});

Is it not supported by the Morris library out of the box?


Solution

  • I figured it out. Morris.js parses the x-axis as timestamp by default. To disable this use parseTime: false. After disabling the parseTime, the x-axis will start taking string input without any issues.

    Optionally you can then use xLabels and xLabelFormat to define the custom format for the x-axis month names like this:

        const monthNames = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
        ];
        Morris.Area({
            element: 'areaChart',
            data: [
                {y: 1, a: 10},
                {y: 2, a: 20},
                {y: 3, a: 30},
                {y: 4, a: 40},
                {y: 5, a: 50},
                {y: 6, a: 60}
            ],
            xkey: 'y',
            parseTime: false,
            ykeys: ['a'],
            xLabelFormat: function (x) {
                var index = parseInt(x.src.y);
                return monthNames[index];
            },
            xLabels: "month",
            labels: ['Series A'],
            lineColors: ['#a0d0e0', '#3dbeee'],
            hideHover: 'auto'
    
        });
    

    Output

    enter image description here