I’m wondering if ChartJS exposes an API for plugins that allows us to obtain the coordinate of a null
point that has been "Spanned" by ChartJS?
For example as illustrated in this question ChartJS enables smooth curves through null
points when settings spanGaps
to `true.
So we could have data points like this.
data: [7, null, 11, null, 5 , null, 8, null, 3, null, 7],
Corresponding to these labels.
["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Blue", "Yellow", "Green", "Purple", "Green"],
Is there a way ( Perhaps via the Plugin API ) to get the values of the nulls?
So for a given quadratic curve that chart JS draws for:
data: [7, null, 11, null, 5 , null, 8, null, 3, null, 7],
We could call for example:
const arr = ChartJSPluginAPI.deriveNulls(data);
And get something like:
data: [7, 8, 11, 6, 5 , 6, 8, 4, 3, 5, 7],
Thoughts?
2
Answers
Finding the interpolated values as they are calculated by chart.js is
not trivial, because chart.js performs the interpolation in graphical mode
only, so we have to get the graphical values of the existing points
for the relevant datasets meta,
perform the interpolation, and then get back to the real space, using
the y-axis scaling.
This is however safer than trying to emulate the interpolation mathematically in real space.
The first thing in finding the intermediate values is to identify the
functions used by chart.js to interpolate all the values of the curves;
there are three functions:
_steppedInterpolation
forstepped
line charts,
_bezierInterpolation
if there is atension
option set,and the default linear interpolation as
_pointInLine
.Note that if modules are used, the
helpers
module needs to be importedseparately.
An important point is to perform the computation after the animation is
completed, since for instance the bezier coefficients (if bezier interpolation
was used) are constantly recomputed during the animation, and their final
values can only be obtained after the animation is
finalized. So, we implement the computation in the animation’s
onComplete
handler:
This solution assumes the index axis is
x
and the value axis isy
;it should work regardless of the
type
of thex
axis (category
,linear
,time
, etc.).Here’s a full snippet with this solution applied to the OP example.
Depending on your Chart (and options) one could calculate the points yourself. You just would have to check the chatjs code on github, too match the functions, how the lines are generated and create/find a function that gives you the points.
Here a crude demo:
(this demo just works with max one gap and the beizer curve, but with better math skills more is possible)