How to draw bar chart with empty data using Amchart 4?

1.2k views Asked by At

I want show empty/dummy bar chart when no data using amcharts version 4 as shown in below link using amcharts version 3.

Example with amcharts version 3

I have tried something like below, but getting error.

reChartData = am4core.create("exeChart", am4charts.XYChart);
var categoryAxis = reChartData.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "";
var  valueAxis = reChartData.yAxes.push(new am4charts.ValueAxis());
valueAxis.min = 0;
valueAxis.max = 100;
var dataPoint = {
  dummyValue: 0
};
reChartData.data = dataPoint;
var series = reChartData.series.push(new am4charts.ColumnSeries());
series.dataFields.categoryX = "";

Error:

Error: Data fields for series "id-98" are not properly defined.
at e.validateData (charts.js:20)
at t.update (core.js:19)
at core.js:19

@GMStevents and @TonyMontana, can you please share your thoughts as you already discussed on similar issue here ?

1

There are 1 answers

0
Frank Fajardo On BEST ANSWER

Firstly, the error you get is because you are not defining your series dataFields. You need to specify the names of dataFields for your series. For example:

series.dataFields.categoryX = "category";
series.dataFields.valueY = "value";

Secondly, the XYChart.data is an array. You cannot assign an object.

Then to show a message on the chart when there is no data, create a container on the chart and add a label, like so:

if (!reChartData.data || reChartData.data.length === 0){
  const noDataMessagecontainer = reChartData.chartContainer.createChild(am4core.Container);
  noDataMessagecontainer.align = 'center';
  noDataMessagecontainer.isMeasured = false;
  noDataMessagecontainer.x = am4core.percent(50);
  noDataMessagecontainer.horizontalCenter = 'middle';
  noDataMessagecontainer.y = am4core.percent(50);
  noDataMessagecontainer.verticalCenter = 'middle';
  noDataMessagecontainer.layout = 'vertical';

  const messageLabel = noDataMessagecontainer.createChild(am4core.Label);
  messageLabel.text = 'There is no data to show on this chart.';
  messageLabel.textAlign = 'middle';
  messageLabel.maxWidth = 300;
  messageLabel.wrap = true;
}

enter image description here

See sample here