Chart.js Data Points and Labels

John Peters - Dec 2 '19 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player