3

I have an ionic project and am using the following library: http://gionkunz.github.io/chartist-js/index.html

Actually drawing the chart is achieved with the following:

var chart = new Chartist.Line('.ct-chart', {
  series: [
{
  name: 'series-1',
  data: [
    {x: new Date(143134652600), y: 53},
    {x: new Date(143234652600), y: 40},
    {x: new Date(143340052600), y: 45},
    {x: new Date(143366652600), y: 40},
    {x: new Date(143410652600), y: 20},
    {x: new Date(143508652600), y: 32},
    {x: new Date(143569652600), y: 18},
    {x: new Date(143579652600), y: 11}
  ]
},
{
  name: 'series-2',
  data: [
    {x: new Date(143134652600), y: 53},
    {x: new Date(143234652600), y: 35},
    {x: new Date(143334652600), y: 30},
    {x: new Date(143384652600), y: 30},
    {x: new Date(143568652600), y: 10}
  ]
}
 ]
  }, {
axisX: {
type: Chartist.FixedScaleAxis,
divisor: 5,
labelInterpolationFnc: function(value) {
  return moment(value).format('MMM D');
}
}
});

With a DIV:

  <div class="ct-chart ct-perfect-fourth"></div>

Instead of having a hardcoded array for the series as shown above, I would like to build this dynamically through a function call.

Any example of how I might do that?

Thanks!

2 Answers 2

2

You could generate the data with a little randomness and some fixed variables using a generate function. It's probably also nicer to parametize the creation of your chart for easier re-creation later. Chartist also has a update() function that lets you hand it new data and options, so is especially useful for this.

JSFIDDLE

Javascript

var button = document.getElementById('button');
var options = {
    axisX: {
        type: Chartist.FixedScaleAxis,
        divisor: 5,
        labelInterpolationFnc: function(value) {
          return moment(value).format('MMM D');
        }
    }
};
var chart; // initialise the chart variable

function createChart(){
    chart = new Chartist.Line('.ct-chart', changeData(), options);
}

function updateChart(){
    chart.update(changeData());
}

function changeData(){
    var series = [];
    // set up series ranges
    var numberOfSeries = 2;
    var numberOfItems = 8;
    var startDate = 143134652600;
    var endDate = 143579652600;
    var minY = 11;
    var maxY = 53;
    // creates the 'step' each x-axis item should take
    var dateDiff = Math.floor((endDate - startDate) / numberOfItems);
    // alternatively set the step to a whole day etc. (makes endDate unnecessary)
    // var dateDiff = 24 * 60 * 60 * 1000;

    for(var x = 0; x < numberOfSeries; x++){
        var seriesData = [];
        for(var y = 0; y < numberOfItems; y++){
            seriesData.push({
                x: new Date(startDate + (dateDiff*y)),
                y: getRandomInt(minY, maxY)
            })
        }
        series.push({
            name: 'series-'+ (x+1),
            data: seriesData
        });
    }
    // return the data to display in the chart
    return {series:series};
}

/**
 * Returns a random integer between min (inclusive) and max (inclusive)
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

button.addEventListener('click', updateChart);

createChart(); // generate chart initially

HTML

<button id="button">
Change Data
</button>
<div class="ct-chart ct-perfect-fourth"></div>
Sign up to request clarification or add additional context in comments.

Comments

1

This is a rough example; you could replace the input series1, series2 with an array of arrays and make the lower for-loops two wrapped loops to handle multiple series. This would also entail adding the objects to the series array in the outer loop.

For now, try something like this:

function generateJSON(series1, series2) {
  var chartInternal = {
    series: [
      {
      name: 'series-1',
      data: []
      },
      {
      name: 'series-2',
      data: []
      }
      ]
    }, {
      axisX: {
        type: Chartist.FixedScaleAxis,
        divisor: 5,
        labelInterpolationFnc: function(value) {
          return moment(value).format('MMM D');
        }
      }
    };

  for (var i = 0, len = series1.length; i < len; i++) {
    chartInternal.series[0].data.push({x: new Date(series1[i].date), y: series1[i].y});
  }
  for (var i = 0, len = series2.length; i < len; i++) {
    chartInternal.series[1].data.push({x: new Date(series2[i].date), y: series2[i].y});
  }
  return chartInternal;
}

Usage:

var series1 = [
  { date: 1234567, y:52 },
  ... more
];
var series2 = [
  { date: 7654321, y:52 },
  ... more
];
var chart = new Chartist.Line('.ct-chart', generateJSON(series1, series2))

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.