DEV Community

Cover image for Chart.js Data Points and Labels
John Peters
John Peters

Posted on

Chart.js Data Points and Labels

Have you ever tried to plot live data in Chart.js only to find, that only two points at a time are plotted?

Labels
The official documentation doesn't really underscore that there is a one to one relationship on a data point and a corresponding label on the x-axis. In addition, the labels exist at the topmost layer of the chart whereas the data-points exist within one or more data-sets.

The different layers are seen here:

one label per point

And declared via the ChartData interface:

Notice that only one set of "labels" exist for all the data-sets.

chart data interface

Data Points
Chart.js can plot multiple data points on the chart via the ChartDataSets array. This means when new data arrives and there's more than one data-set, the new data must be added to the correct data-set. The only way to discern them is via the index within the data-set array or the label within. Yes data-sets have a single label, not to be confused with the chart.data.labels property.

Updating Data
Simply find the proper data set and set the data to the new livedata array. Like this:

push

Putting It Together

Keeping immutability in mind.

full code

Where getLabels is this:

get labels

JWP2019

Top comments (2)

Collapse
 
emjayess profile image
Matthew J. Sorenson

"there is a one to one relationship on a data point and a corresponding label on the x-axis"

I have been exploring this, and so far have discovered only very hackish ways around it. It seems like "365 points, 12 labels for months" would be a more common use case :/

Collapse
 
jwp profile image
John Peters • Edited

Matthew, would it work if you push ( 365 - 12 ) blank labels and then strategically pushing month values where needed?