DEV Community

Cover image for Chart.js Data Points and Labels
JWP
JWP

Posted on

4 2

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
JWP • Edited

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

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay