I'm trying to swap out data sets in a C3.js graph.
The code I assumed would work based on the C3 docs looks like this:
chart.unload();
chart.load({
columns: [
['data3', 100, 90, 80, 70, 60, 50]
]
});
But this doesn't work. You'll notice that the graph rendered on the following Plunkr renders improperly, so I'm clearly doing something wrong: https://jsfiddle.net/7rfm9om9/
What is the idiomatic way to replace data in a C3 chart?
According to the c3 documentation, the way to do this is to use the unload param of the load function.
chart.load({
unload: true,
columns: ['data1', 100]
});
There are issues with rendering and animations otherwise when trying to use .unload() and then .load().
This note is included in the .unload() documentation:
http://c3js.org/reference.html#api-unload
Note: If you call [the] load API soon after/before unload, unload param of load should be used. Otherwise chart will not be rendered properly because of [cancelation] of animation.
done will be called after data loaded, but it's not after rendering. It's because rendering will finish after some transition and there is some time lag between loading and rendering.
According to the documentation for .load():
http://c3js.org/reference.html#api-load
If unload given, data will be unloaded before loading new data. If true given, all of data will be unloaded. If target ids given as String or Array, specified targets will be unloaded.
Note: unload should be used if some data needs to be unloaded simultaneously. If you call unload API soon after/before load instead of unload param, chart will not be rendered properly because of cancel of animation.
Format would be along the lines of the following snippets:
All Data
chart.load({
unload: true,
columns: [
['data3', 100, 90, 80, 70, 60, 50]
]
});
Specified Targets
chart.load({
unload: ['data1', 'data2'],
columns: [
['data3', 100, 90, 80, 70, 60, 50]
]
});
JSFiddle:
Ah, it appears that chart.unload()
does some asynchronous work that, if you call chart.load()
immediately after in a synchronous fashion, will break the graph.
I got this working by loading the new data in a function passed to chart.unload
's done
callback.
chart.unload({
done: function() {
chart.load({
columns: [
['data3', 100, 90, 80, 70, 60, 50]
]
});
}
});
Working fiddle: https://jsfiddle.net/1g5v1s24/1/
来源:https://stackoverflow.com/questions/35248099/how-to-swap-out-data-via-unload-and-load-in-c3-js