Dynamically adding charts to the same Root
This demo shows how we can dynamically add live charts to a Container in a single Root element.
Open in:New tab
/** * --------------------------------------- * This demo was created using amCharts 5. * * For more information visit: * https://www.amcharts.com/ * * Documentation is available at: * https://www.amcharts.com/docs/v5/ * --------------------------------------- */
// Create root and chartvar root = am5.Root.new("chartdiv");
root.setThemes([am5themes_Animated.new(root)]);
var container = root.container.children.push( am5.Container.new(root, { width: am5.p100, height: am5.p100, layout: root.horizontalLayout }));
var button = root.container.children.push( am5.Button.new(root, { label: am5.Label.new(root, { text: "Add Chart" }) }));
button.events.on("click", addChart);
function addChart() { var chart = container.children.push( am5percent.PieChart.new(root, { layout: root.verticalLayout }) );
// Define data var data = [ { country: "France", sales: Math.round(Math.random() * 10000 + 3000) }, { country: "Spain", sales: Math.round(Math.random() * 10000 + 3000) }, { country: "United Kingdom", sales: Math.round(Math.random() * 10000 + 3000) } ];
// Create series var series = chart.series.push( am5percent.PieSeries.new(root, { name: "Series", valueField: "sales", categoryField: "country" }) );
series.labels.template.set("forceHidden", true); series.ticks.template.set("forceHidden", true);
series.data.setAll(data);}
addChart();<div id="chartdiv"></div>body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";}
#chartdiv { width: 100%; height: 95vh;}dynamically-adding-charts-to-the-same-root