1

I am trying to generate an area graph for two (or more) products i.e. Mosquito Repellents and Liquid Soap. I am using the JavaScript library CanvasJS to do that. The problem is that I need approximately 2000 data points instead of 4 hardcoded here and the problem is that I am unable to generate a for loop for two (or more) products that will do this for me. Can anyone help me on how to create this loop?

var chart = new CanvasJS.Chart("chartContainer", {
    data: [{
        type: "area",
        name: "Mosquito Repellents",
        showInLegend: "true",
        dataPoints: [{
                y: 83450,
                label: "spring"
            }, {
                y: 51240,
                label: "summer"
            }, {
                y: 64120,
                label: "fall"
            }, {
                y: 71450,
                label: "winter"
            }

        ]
    }, {
        type: "area",
        name: "Liquid Soap",
        showInLegend: "true",
        dataPoints: [{
                y: 20140,
                label: "spring"
            }, {
                y: 30170,
                label: "summer"
            }, {
                y: 24410,
                label: "autumn"
            }, {
                y: 38120,
                label: "fall"
            }

        ]
    }]
});
2
  • What's the source of data to generate datapoints array? Commented Jun 22, 2015 at 22:24
  • Random would do at this point. The final concept would be to gain data from a database, but this is down the road. Commented Jun 22, 2015 at 22:26

1 Answer 1

3

You can use the Math.random function and a function to get it done. The function takes two parameters to set the lower and upper limits of the random y value.

var mosquitoRepellentsDataPoints = generateDataPoints(10000, 40000),
    liquidSoapDataPoints = generateDataPoints(10000, 40000);

var chart = new CanvasJS.Chart("chartContainer", {
    data: [{
        type: "area",
        name: "Mosquito Repellents",
        showInLegend: "true",
        dataPoints: mosquitoRepellentsDataPoints
    }, {
        type: "area",
        name: "Liquid Soap",
        showInLegend: "true",
        dataPoints: liquidSoapDataPoints
    }]
});


function generateDataPoints(lowerLimit, upperLimit) {
    var i,
        arr = [],
        seasons = ['spring', 'summer', 'fall', 'winter'];

    for (i = 0; i < 2000; i++) {
        arr.push({
            y: lowerLimit + Math.round(Math.random() * (upperLimit - lowerLimit)),
            label: seasons[Math.floor(Math.random() * seasons.length)]
        });
    }
    return arr;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.