Replies: 1 comment
-
|
You can absolutely build a custom plugin that internally uses Here is the approach: import annotationPlugin from "chartjs-plugin-annotation";
import { Chart } from "chart.js";
// Make sure annotation plugin is registered
Chart.register(annotationPlugin);
const waterfallPlugin = {
id: "waterfall",
beforeInit(chart) {
const waterfallOpts = chart.options.plugins.waterfall;
if (!waterfallOpts) return;
// Convert simple values into floating bar data + annotations
const values = waterfallOpts.values; // e.g. [100, -20, 30, -10, 50]
const labels = waterfallOpts.labels;
let cumulative = 0;
const floatingData = [];
const annotations = {};
values.forEach((val, i) => {
const start = cumulative;
cumulative += val;
floatingData.push([Math.min(start, cumulative), Math.max(start, cumulative)]);
// Add connector line annotation between bars
if (i < values.length - 1) {
annotations[`connector-${i}`] = {
type: "line",
xMin: i + 0.4,
xMax: i + 0.6,
yMin: cumulative,
yMax: cumulative,
borderColor: "grey",
borderWidth: 1,
borderDash: [4, 4],
};
}
});
// Inject computed data into chart config
chart.data.datasets[0].data = floatingData;
chart.data.labels = labels;
// Merge annotations into existing annotation config
chart.options.plugins.annotation = chart.options.plugins.annotation || {};
chart.options.plugins.annotation.annotations = {
...chart.options.plugins.annotation.annotations,
...annotations,
};
},
};
Chart.register(waterfallPlugin);Then usage becomes: new Chart(ctx, {
type: "bar",
data: { datasets: [{ backgroundColor: ["green", "red", "green", "red", "green"] }] },
options: {
plugins: {
waterfall: {
values: [100, -20, 30, -10, 50],
labels: ["Start", "Loss", "Gain", "Loss", "Gain"],
},
},
},
});The trick is to use One thing to watch: make sure your plugin is registered after the annotation plugin, or use |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
In my case, I would like to write a custom waterfall chart plugin.
I can already simulate it using the annotation plugin.
Now I want to wrap the whole logic into a custom plugin, so all I need to use it is just simply passing the values for each bar (without needing to pass
[minValue, maxValue]like in typical floating bar)How can I achieve this?
Beta Was this translation helpful? Give feedback.
All reactions