Home > Software design >  google graph how to display empty graph when there is no data
google graph how to display empty graph when there is no data

Time:11-13

I have a google graph where it is working as expected when there is data

enter image description here

But when there is no data it is displaying a message as follows

Data column(s) for axis #0 cannot be of type string

enter image description here

Here is the code that I am trying out

function drawBarChar() {
    show('loading5', true);
    var data = JSON.stringify({
        'GraphId': 1,
        'startDt': $("#from-date").val(),
        'endDt': $("#to-date").val()
    });
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            show('loading5', false);
            var data = google.visualization.arrayToDataTable(r);

            var view = new google.visualization.DataView(data);
            view.setColumns([0, 1,
                {
                    calc: "stringify",
                    sourceColumn: 1,
                    type: "string",
                    role: "annotation"
                }
            ]);

            var options = {
                width: 500,
                height: 400,
                colors: ["#6cc49c"],
                bar: { groupWidth: "65%" },
                legend: { position: "none" }
            };

            var chart = new google.visualization.BarChart($("#vesselGraph")[0]);
            chart.draw(data, options);
        },
        failure: function (r) {
            alert(r.d);
        },
        error: function (r) {
            alert(r.d);
        }
    });
}



public JsonResult LoadGraph(int GraphId, DateTime? startDt = null, DateTime? endDt = null)
{
    List<object> chartData = new List<object>
    {
       new object[]
       {
          "Name", "Count"
       }
    };
    DataTable table = db.GetAllFromDb("up_DashboardList", "@dashBoardId", GraphId,
            "@startDate", startDt.Value.ToString("yyyy-MM-dd"), "@endDate", endDt.Value.ToString("yyyy-MM-dd")); // when the table has no rows it is displaying that error message
    foreach (DataRow row in table.Rows)
        {
            chartData.Add(new object[]
            {
                row["TypeName"], row["DataCount"]
            });
        }
        return Json(chartData);
}

After @whitehat suggested

enter image description here

CodePudding user response:

first, need to understand how arrayToDataTable works.
it uses the data provided in the array to determine each column type.

if only the column headings are provided,
there is no data to determine the types.
and it defaults both column types to string.

all the chart types in the 'corechart' package expect the first series to be a number, date, something other than a string.
so we cannot use arrayToDataTable to create the data table,
if there is a chance of no data existing.

we must use the DataTable default constructor.

var data = new google.visualization.DataTable();

then we can test the data array received to determine if data exists.
if no data exists, we can add a blank row to draw a blank chart.

in this example, we receive the data in the following format.

var r = [['Name', 'Count']];

we remove the first row / array to use as the column headings.

var cols = r.splice(0, 1);
cols[0].forEach(function (col, index) {
  if (index === 0) {
    data.addColumn('string', col);
  } else {
    data.addColumn('number', col);
  }
});

then determine if additional rows exist,
if not add a blank row.

if (r.length > 0) {
  data.addRows(r);
} else {
  data.addRow(['', null]);
}

see following working snippet...

var r = [['Name', 'Count']];

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable();
  var cols = r.splice(0, 1);
  cols[0].forEach(function (col, index) {
    if (index === 0) {
      data.addColumn('string', col);
    } else {
      data.addColumn('number', col);
    }
  });
  if (r.length > 0) {
    data.addRows(r);
  } else {
    data.addRow(['', null]);
  }

  var view = new google.visualization.DataView(data);
  view.setColumns([0, 1, {
    calc: "stringify",
    sourceColumn: 1,
    type: "string",
    role: "annotation"
  }]);

  var options = {
    width: 500,
    height: 400,
    colors: ["#6cc49c"],
    bar: { groupWidth: "65%" },
    legend: { position: "none" }
  };

  var chart = new google.visualization.BarChart($("#vesselGraph")[0]);
  chart.draw(data, options);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="vesselGraph"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related