How to use the load() and unload() APIs in C3.js
C3.js abstracts away the intricacies of low-level charting libraries, allowing developers to focus on their data and design intent. The real magic lies in C3.js’s APIs for dynamic manipulation. In this Answer, we’ll discuss the load() and unload() APIs of C3.js.
The load() API
The load() API in C3.js allows us to dynamically load data and update an existing chart after it has been rendered. Here’s the syntax of the load() API:
chart.load({// Add your chart data here});
The above syntax invokes a function called load() on a chart object named chart.
Lines 3–5: We add links to external CSS and JavaScript libraries required for creating charts using C3.js and D3.js.
Lines 6–14: We add the CSS rules for styling the elements on the page. It centers the content of the div with the
containerclass and horizontally centers the chart using thetext-align: center;andmargin: 0 auto;properties, respectively.Lines 17–20: We add the heading, chart container, and button to load data.
Lines 23–56: We initialize a chart using C3.js and set up an event listener for the
Load Databutton. When the button is clicked, it loads new data into the existing chart.
The unload() API
The unload() API unloads data from the chart. It replaces or removes specific series or all data points from the chart. Here’s the syntax of the unload() API:
chart.unload({// Add your chart data here});
The above syntax invokes a function called unload() on a chart object named chart.
Lines 62–64: When the button with the ID
unloadis clicked, the JavaScript function associated with it is triggered. Inside this function, there’s a command to remove specific data series (set1andset2) from the chart. This action effectively unloads these data series from the chart, meaning they’re no longer displayed or considered in the visualization.
Conclusion
The load() and unload() APIs provide powerful ways to manage data dynamically in C3.js charts. We can use the load() API to update data, and the unload() API to selectively remove data. Experimenting with these APIs allows us to create interactive and responsive visualizations.
Free Resources