javascriptarrayshighcharts

Create the xAxys with a array of strings instead of an array of integers - Highcharts


I need to use an array of strings instead of an array of integers to create my xAxis on Highcharts.

Has anyone already tried to do this or can help me make this happen?

My mock data to be used on this chart will be something like:

var weekNoArray = [32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 34, 34, 34, 34, 34, 34],
    retailerNamesArray = ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f'],
    clicksArray = [43, 48, 62, 63, 43, 39, 27, 30, 43, 49, 34, 24, 47, 45, 59, 64, 48, 47],
    series = [];

The retailerNamesArray variable needs to be used to create my xAxis.

What I have already tried to generate the series:

series = generateData(weekNoArray, retailerNamesArray, clicksArray);

function generateData(weekNoArray, retailerNamesArray, clicksArray) {
    var ret = {},
        ps = [],
        series = [],
        len = weekNoArray.length;

    // Concatenate to get points
    for (var i = 0; i < len; i++) {
        ps[i] = {
            x: weekNoArray[i],
            y: clicksArray[i],
            n: retailerNamesArray[i]
        };
    }
    retailerNamesArray = [];
    // Generate series and split points
    for (i = 0; i < len; i++) {
        var p = ps[i],
            sIndex = $.inArray(p.n, retailerNamesArray);

        if (sIndex < 0) {
            sIndex = retailerNamesArray.push(p.n) - 1;
            series.push({
                name: p.n,
                data: []
            });
        }
        series[sIndex].data.push(p);
    }
    return series;
}
$('#container').highcharts({
    title: {
        text: 'Retailer Clicks',
        x: -20 // center
    },
    subtitle: {
        text: 'Date',
        x: -20
    },
    yAxis: {
        title: {
            text: 'Clicks'
        },
        plotLines: [{
            value: 0,
            width: 1,
            color: '#808080'
        }]
    },
    tooltip: {
        valueSuffix: '°C'
    },
    legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle',
        borderWidth: 0
    },
    series: series
});

Running example: Fiddle 1


Solution

  • In case of this code weekNoArray where used to set x axis values and xAxis of linear type. Now if you want to use category type axis you should at least:

    Example: http://jsfiddle.net/rt4pthvn/