Add or remove a series from the chart dynamically

17 Feb 20224 minutes to read

You can add or remove the chart series dynamically by using the addSeries or removeSeries method.

To add or remove the series dynamically, follow the given steps:

Step 1:

To add a new series to chart dynamically, pass the series value to the addSeries method.

To remove the new series from chart dynamically, pass the series index to the removeSeries method.

<button id="add">Add</button>
<button id="remove">Remove</button>
@Html.EJS().Chart("container").PrimaryXAxis(px => px.Title("Years").
                       ValueType(Syncfusion.EJ2.Charts.ValueType.Category)).Series(series =>
                       {
                           series.Type(
              Syncfusion.EJ2.Charts.ChartSeriesType.Column
          ).DataSource(ViewBag.dataSource).Name("Product X").XName("x").YName("yValue").Add();
                       }
                       ).PrimaryYAxis(py => py.Title("Profit ($)")).Title("Sales History of Product X").Render()
<script>
    document.getElementById("add").onclick = function () {
        var chart = document.getElementById("container").ej2_instances[0];
        chart.addSeries([{
            type: 'Column',
            dataSource: [{ x: 'John', y: 11000 }, { x: 'Jake', y: 16000 }, { x: 'Peter', y: 19000 },
            { x: 'James', y: 12000 }, { x: 'Mary', y: 10700 }],
            xName: 'x', width: 2,
            yName: 'y'
        }]);
    };
    document.getElementById("remove").onclick = function () {
        var chart = document.getElementById("container").ej2_instances[0];
        chart.removeSeries(1);
    }
</script>
public ActionResult Index()
        {
            List<ColumnChartData> chartData = new List<ColumnChartData>
            {
                new ColumnChartData { x= "John", yValue= 10000, yValue1=37, yValue2=38 },
                new ColumnChartData { x= "Jake", yValue= 12000, yValue1=23, yValue2=17 },
                new ColumnChartData { x= "Peter", yValue= 18000, yValue1=18, yValue2=26 },
                new ColumnChartData { x= "James", yValue= 11000, yValue1=18, yValue2=26 }
            };
            ViewBag.dataSource = chartData;
            return View();
        }
        public class ColumnChartData
        {
            public string x;
            public double yValue;
            public double yValue1;
            public double yValue2;
        }