locked
Chart.js PieChart how to display No data? RRS feed

  • Question

  • User-1104215994 posted

    Hi,

    I would like to display no data if there is no data, I added this but It did NOT display "No Data to Display". How can I achieve it?

     Chart.plugins.register({
                    afterDraw: function(chart) {
                        if (chart.data.datasets.length === 0) {
                            // No data is present
                            var ctx = chart.chart.ctx;
                            var width = chart.chart.width;
                            var height = chart.chart.height
                            chart.clear();
          
                            ctx.save();
                            ctx.textAlign = 'center';
                            ctx.textBaseline = 'middle';
                            ctx.font = "20px 'Helvetica'";
                            ctx.fillText('No data to display', width / 2, height / 2);
                            ctx.restore();
                        }
                    }
                });

    Best Regards.

    Sunday, December 1, 2019 10:46 AM

Answers

  • User665608656 posted

    Hi cenk,

    According to your code, you need to add judgment in the ShowPie method in advance to judge the length of the incoming parameter data array.

    If it is greater than 0, then follow the original writing method. If it is less than or equal to 0, then set the labels and datasets values to the empty array.

    You can change your js code as follow:

            function ShowPie(data) {
                var PieChartData =
                {
                    labels: [],
                    datasets: []
                };
                var PieChartData1 =
                {
                    labels: [],
                    datasets: []
                };
                if (data.length > 0) {
                    PieChartData =
                        {
                            labels: data[0].status_ListRazer,
                            datasets: [
                                {
                                    label: 'Razer/Zula Database',
                                    backgroundColor: colors,
                                    borderWidth: 2,
                                    data: data[0].count_ListRazer,
                                }
                            ]
                        };
                    PieChartData1 =
                        {
                            labels: data[1].status_ListRazer,
                            datasets: [
                                {
                                    label: 'Our Database',
                                    backgroundColor: colors,
                                    borderWidth: 2,
                                    data: data[1].count_ListRazer,
                                }
                            ]
                        };
                }
    
                if (typeof chart != "undefined") {
                    chart.destroy();
                }
                if (typeof chart1 != "undefined") {
                    chart1.destroy();
                }
                var ctx1 = document.getElementById("pie-chart1").getContext("2d");
                chart = new Chart(ctx1,
                    {
                        type: 'pie',
                        data: PieChartData1,
                        options:
                        {
                            legend: {
                                position: 'bottom', padding: 5,
                                labels: {
                                    pointStyle: 'circle',
                                    usePointStyle: true,
                                    fontColor: function (data) {
                                        return data;
                                    } 
                                }
                            },
                            title:
                            {
                                display: true,
                                text: "Razer/Zula Database"
                            },
                            responsive: true,
                            maintainAspectRatio: false,
                            animation: {
                                easing: 'easeInOutQuart',
                                duration: 2000
                            }
                        }
                    });
    
                var ctx = document.getElementById("pie-chart").getContext("2d");
                chart1 = new Chart(ctx,
                    {
                        type: 'pie',
                        data: PieChartData,
                        options:
                        {
                            legend: {
                                position: 'bottom', padding: 5, labels: {
                                    pointStyle: 'circle',
                                    usePointStyle: true,
                                    fontColor: function (data) {
                                        return data;
                                    } 
                                }
                            },
                            title:
                            {
                                display: true,
                                text: "Our Database"
                            },
                            responsive: true,
                            maintainAspectRatio: false,
                            animation: {
                                easing: 'easeInBounce',
                                duration: 2000
                            }, 
                        }
                    });
            }

    This is the result when there is an empty data pass from controller:

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 3, 2019 2:30 AM

All replies

  • User665608656 posted

    Hi cenk,

    I would like to display no data if there is no data, I added this but It did NOT display "No Data to Display". How can I achieve it?

    The code you provided is correct, but you need to bind the data source correctly.

    When there is no data, you need to assign an empty array to the dataset in the data attribute of chart, so as to ensure that the afterdraw method can be executed correctly.

    I have done a case of using select to switch pie chart data source. When '3' is selected, no data source is transferred, so what you need will be displayed.

    !DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
        <script src="../Scripts/jquery-3.2.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.min.js"></script>
        <script type="text/javascript">
            $(function () {
                var dataSet = [{
                    backgroundColor: ['#00e600', '#e6e600', '#E60000'],
                    data: [1, 1, 1] //1, 1, 1 are example values
                }];
                BindChart(dataSet);
                $('select').on('change', function () {
                    if ($(this).val() == '1') {
                        dataSet = [{
                            backgroundColor: ['#00e600', '#e6e600', '#E60000'],
                            data: [1, 1, 1] //1, 1, 1 are example values
                        }];
    
                    } else if ($(this).val() == '2') {
                        dataSet = [{
                            backgroundColor: ['#00e600', '#e6e600', '#E60000'],
                            data: [10, 50, 40] //1, 1, 1 are example values
                        }];
                    } else { // no data when select '3'
                        dataSet = [];
                    }
                    BindChart(dataSet);
                });
    
    
            });
            var myChart;
            function BindChart(dataSet) {
                var pieChartData =
                {
                    labels: ['GOOD', 'WARN', 'BAD'],
                    datasets: dataSet
                };
                var pieChartContext = document.getElementById("piechart").getContext("2d");
                if (myChart) {
                    myChart.destroy();
                };
                myChart = new Chart(pieChartContext, {
                    type: 'pie',
                    data: pieChartData,
                    options: {
                        legend: {
                            display: true,
                            position: 'right'
                        },
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
    
                Chart.plugins.register({
                    afterDraw: function (chart) {
                        if (chart.data.datasets.length === 0) {
                            // No data is present
                            var ctx = chart.chart.ctx;
                            var width = chart.chart.width;
                            var height = chart.chart.height
                            chart.clear();
    
                            ctx.save();
                            ctx.textAlign = 'center';
                            ctx.textBaseline = 'middle';
                            ctx.font = "20px 'Helvetica'";
                            ctx.fillText('No data to display', width / 2, height / 2);
                            ctx.restore();
                        }
                    }
                });
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div style="width: 300px; height: 300px;">
                <select>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                </select>
                <canvas id="piechart"></canvas>
            </div>
        </form>
    </body>
    </html>
    

    Here is the result of this work demo:

    Here is also an example about chart.js to show 'no data', you can refer to it : https://jsfiddle.net/x04ptfuu/

    Best Regards,

    YongQing.

    Monday, December 2, 2019 8:04 AM
  • User-1104215994 posted

    I am trying to send the empty list as follows but still don't work.

    [HttpGet]
            public JsonResult PieChartDraw(string sDate, string eDate)
            {
                try
                {
                    
                    List<PieData> pieDatas = new List<PieData>(); // the class to store the data you want to pass to view
    
                    var startDate = DateTime.Today;
                    var endDate = DateTime.Today.AddDays(1);
                    if (sDate != null && eDate != null) // judge if the view select the date 
                    {
                        startDate = DateTime.ParseExact(sDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                        endDate = DateTime.ParseExact(eDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                    }
    
                   
    
                    //Our Database
                    var result = _context.GameBanks
                        .Where(m => m.RequestDateTime >= startDate && m.RequestDateTime < endDate && m.ResponseDateTime != null)
                        .GroupBy(p => p.Status)
                        .Select(g => new {Count = g.Count(), Status = g.Key})
                        .ToList();
    
                    var resultList = string.Empty;
                    var nameList = new List<string>();
    
                    foreach (var element in result)
                    {
                        resultList = resultList + element.Count + ",";
    
                        switch (Convert.ToInt32(element.Status))
                        {
                            case 0:
    
                                nameList.Add("UNCERTAIN");
                                break;
                            case 1:
    
                                nameList.Add("CONFIRM");
                                break;
                            case 2:
    
                                nameList.Add("CANCEL");
                                break;
                        }
                    }
    
                    // the first pie data added to class 
                    PieData pieData1 = new PieData();
                    if (result.Count > 0)
                    {
                        pieData1.Count_List = resultList.TrimEnd(',').Trim().Split(',').ToList();
                    }
                    else
                    {
                        pieData1.Count_List = new List<string>();
                    }
                    
                    
                    pieData1.Status_List = nameList;
                    pieDatas.Add(pieData1);
    
                    //RAZER Database
                    var resultRazer = _context.GameConfirmResponses
                        .Where(m => m.requestDateTime >= startDate && m.requestDateTime < endDate)
                        .GroupBy(p => p.status)
                        .Select(g => new {Count = g.Count(), Status = g.Key})
                        .ToList();
    
                    var resultListRazer = string.Empty;
                    var nameListRazer = new List<string>();
    
                    foreach (var element in resultRazer)
                    {
                        resultListRazer = resultListRazer + element.Count + ",";
    
                        switch (Convert.ToInt32(element.Status))
                        {
                            case 0:
    
                                nameListRazer.Add("UNCERTAIN");
                                break;
                            case 1:
    
                                nameListRazer.Add("CONFIRM");
                                break;
                            case 2:
    
                                nameListRazer.Add("CANCEL");
                                break;
                        }
                    }
    
                    // the second pie data added to class 
                    PieData pieData2 = new PieData();
                    if (resultRazer.Count > 0)
                    {
                        pieData2.Count_List = resultListRazer.TrimEnd(',').Trim().Split(',').ToList();
                    }
                    else
                    {
                        pieData2.Count_List = new List<string>();
                    }
    
                    pieData2.Status_List = nameListRazer;
                    pieDatas.Add(pieData2);
    
                    return new JsonResult(pieDatas);
                }
                catch (Exception e)
                {
                    var timestamp = DateTime.UtcNow;
                    //NLOG
                    NLog(logger2, "Draw Pie Chart "+e.Message, timestamp, 0);
                    throw new Exception(e.Message);
                    
                }
            }

    Here is the script:

    <script>
                $(document).ready(function () {
                    $.ajax({
                        type: "GET",
                        url: '/GameBanks/PieChartDraw',
                        dataType: 'json',
                        success: function (data) {
                            ShowPie(data);
                        }
                    });
    
                    $("#datepickerStart").datepicker({ dateFormat: "dd/mm/yy" }).datepicker("setDate", new Date());
                    $("#datepickerEnd").datepicker({ dateFormat: "dd/mm/yy" }).datepicker("setDate", new Date());
                    $("#btn_pie_chart").on('click',
                        function () {
                            var from = $("#datepickerStart").val();
                            var to = $("#datepickerEnd").val();
                            //var game = $("#game option:selected").val();
    
                            var serviceURL = '/GameBanks/PieChartDraw?sDate=' + from + '&eDate=' + to;
    
    
                            $.ajax({
                                type: "GET",
                                url: serviceURL,
                                dataType: 'json',
                                success: function (data) {
                                    ShowPie(data);
                                }
                            });
    
                        });
                    $("#btn_excel").on('click',
                        function() {
                            var from = $("#datepickerStart").val();
                            var to = $("#datepickerEnd").val();
                            //var game = $("#game option:selected").text();
    
                            var serviceURL = '/GameBanks/ExportStatus?sDate=' + from + '&eDate=' + to ;
                            
                            document.location.href = serviceURL;
    
                        });
    
                });
    
                Chart.plugins.register({
                    afterDraw: function(chart) {
                        if (chart.data.datasets.length === 0) {
                            // No data is present
                            var ctx = chart.chart.ctx;
                            var width = chart.chart.width;
                            var height = chart.chart.height
                            chart.clear();
          
                            ctx.save();
                            ctx.textAlign = 'center';
                            ctx.textBaseline = 'middle';
                            ctx.font = "20px 'Helvetica'";
                            ctx.fillText('No data to display', width / 2, height / 2);
                            ctx.restore();
                        }
                    }
                });
    
                var chart, chart1;
    
                function ShowPie(data) { // this paramater to show label and data
                    var PieChartData =
                    {
                        labels: data[0].status_List,
                        datasets: [
                            {
                                label: 'Razer/Zula Database',
                                backgroundColor: [
                                    "#f1f106",
                                    "#3fb847",
                                    "#190be0",
                                    "#99e5e5",
                                    "#f7bd83"
                                ],
                                borderWidth: 2,
                                data: data[0].count_List
                            }
                        ]
                    };
                    var PieChartData1 =
                    {
                        labels: data[1].status_List,
                        datasets: [
                            {
                                label: 'Our Database',
                                backgroundColor: [
                                    "#f1f106",
                                    "#3fb847",
                                    "#190be0",
                                    "#99e5e5",
                                    "#f7bd83"
                                ],
                                borderWidth: 2,
                                data: data[1].count_List
                            }
                        ]
                    };
                    // ensure the pie chart to clear preview data
                    if (typeof chart != "undefined") {
                        chart.destroy();
                    }
                    if (typeof chart1 != "undefined") {
                        chart1.destroy();
                    }
                    var ctx1 = document.getElementById("pie-chart1").getContext("2d");
                    chart = new Chart(ctx1,
                        {
                            type: 'pie',
                            data: PieChartData1,
                            options:
                            {
                                legend: { position: 'bottom', padding: 5, labels: { pointStyle: 'circle', usePointStyle: true } },
                                title:
                                {
                                    display: true,
                                    text: "Razer/Zula Database"
                                },
                                responsive: true,
                                maintainAspectRatio: false,
                                animation: {
                                    easing: 'easeInOutBack',
                                    duration: 2000
                                }
                            }
                            
                        });
    
                    var ctx = document.getElementById("pie-chart").getContext("2d");
                    chart1 = new Chart(ctx,
                        {
                            type: 'pie',
                            data: PieChartData,
                            options:
                            {
                                legend: { position: 'bottom', padding: 5, labels: { pointStyle: 'circle', usePointStyle: true } },
                                title:
                                {
                                    display: true,
                                    text: "Our Database"
                                },
                                responsive: true,
                                maintainAspectRatio: false,
                                animation: {
                                    easing: 'easeInOutBounce',
                                    duration: 2000
                                }
    
                            }
                        });
    
                    
                }
                
    
            </script>

    Monday, December 2, 2019 10:46 AM
  • User665608656 posted

    Hi cenk,

    According to your code, you need to add judgment in the ShowPie method in advance to judge the length of the incoming parameter data array.

    If it is greater than 0, then follow the original writing method. If it is less than or equal to 0, then set the labels and datasets values to the empty array.

    You can change your js code as follow:

            function ShowPie(data) {
                var PieChartData =
                {
                    labels: [],
                    datasets: []
                };
                var PieChartData1 =
                {
                    labels: [],
                    datasets: []
                };
                if (data.length > 0) {
                    PieChartData =
                        {
                            labels: data[0].status_ListRazer,
                            datasets: [
                                {
                                    label: 'Razer/Zula Database',
                                    backgroundColor: colors,
                                    borderWidth: 2,
                                    data: data[0].count_ListRazer,
                                }
                            ]
                        };
                    PieChartData1 =
                        {
                            labels: data[1].status_ListRazer,
                            datasets: [
                                {
                                    label: 'Our Database',
                                    backgroundColor: colors,
                                    borderWidth: 2,
                                    data: data[1].count_ListRazer,
                                }
                            ]
                        };
                }
    
                if (typeof chart != "undefined") {
                    chart.destroy();
                }
                if (typeof chart1 != "undefined") {
                    chart1.destroy();
                }
                var ctx1 = document.getElementById("pie-chart1").getContext("2d");
                chart = new Chart(ctx1,
                    {
                        type: 'pie',
                        data: PieChartData1,
                        options:
                        {
                            legend: {
                                position: 'bottom', padding: 5,
                                labels: {
                                    pointStyle: 'circle',
                                    usePointStyle: true,
                                    fontColor: function (data) {
                                        return data;
                                    } 
                                }
                            },
                            title:
                            {
                                display: true,
                                text: "Razer/Zula Database"
                            },
                            responsive: true,
                            maintainAspectRatio: false,
                            animation: {
                                easing: 'easeInOutQuart',
                                duration: 2000
                            }
                        }
                    });
    
                var ctx = document.getElementById("pie-chart").getContext("2d");
                chart1 = new Chart(ctx,
                    {
                        type: 'pie',
                        data: PieChartData,
                        options:
                        {
                            legend: {
                                position: 'bottom', padding: 5, labels: {
                                    pointStyle: 'circle',
                                    usePointStyle: true,
                                    fontColor: function (data) {
                                        return data;
                                    } 
                                }
                            },
                            title:
                            {
                                display: true,
                                text: "Our Database"
                            },
                            responsive: true,
                            maintainAspectRatio: false,
                            animation: {
                                easing: 'easeInBounce',
                                duration: 2000
                            }, 
                        }
                    });
            }

    This is the result when there is an empty data pass from controller:

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 3, 2019 2:30 AM