1

I have an array of objects that have an x and y property. How do I get the correct property values to be used in the correct places in a chart.js chart?

I have the following .js code so far

var lineChartData = {
labels: progress.y,
datasets: [{
    label: 'My First dataset',
    borderColor: window.chartColors.red,
    backgroundColor: window.chartColors.red,
    fill: false,
    data: progress,
    yAxisID: 'y-axis-1'
   }]
};

The array object is called progress. I think the data: progress is picking up the x property value automatically, but the labels: progress.y isn't.

Any ideas how I get the y axis label to work?

EDIT: The progress object looks like this when I view the page source

var progress = [{"y":1624,"x":0},{"y":1606,"x":1}, etc
3
  • Are you able to post the progress object? Is it showing the dataset? Commented May 4, 2018 at 20:18
  • I've updated with how the progress object looks. Commented May 4, 2018 at 20:19
  • Never mind I got the answer! Commented May 4, 2018 at 20:21

2 Answers 2

1

I just selected the x property from the array like so:

labels: progress.map(function (a) { return a.x; })
Sign up to request clarification or add additional context in comments.

Comments

0

Using objects is possible in Chart.js 3.x and it can be an advantage (e.g. use other properties for tooltips).

Use parsing to specify the property for axes.

Example from chartjs.org:

type: 'bar',
data: {
    datasets: [{
        data: [{id: 'Sales', nested: {value: 1500}}, {id: 'Purchases', nested: {value: 500}}]
    }]
},
options: {
    parsing: {
        xAxisKey: 'id',
        yAxisKey: 'nested.value'
    }
}

Example 2 from chartjs.org:

const data = [{x: 'Jan', net: 100, cogs: 50, gm: 50}, {x: 'Feb', net: 120, cogs: 55, gm: 75}];
const cfg = {
    type: 'bar',
    data: {
        labels: ['Jan', 'Feb'],
        datasets: [{
            label: 'Net sales',
            data: data,
            parsing: {
                yAxisKey: 'net'
            }
        }, {
            label: 'Cost of goods sold',
            data: data,
            parsing: {
                yAxisKey: 'cogs'
            }
        }, {
            label: 'Gross margin',
            data: data,
            parsing: {
                yAxisKey: 'gm'
            }
        }]
    },
};

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.