Search code examples
javascriptchartsmapsamcharts

Map to Piecharts - Amcharts


I am trying to customize this chart demo by Amcharts:

https://www.amcharts.com/demos/countries-morphing-to-pie-charts/

I cannot figure out how and where I can give my data as input. I see that the example uses random data for the pie charts, setting them with this line of code:

dataItem.value = Math.round(Math.random() * 100);

I need to have custom values for the piechart of each country in the chart.

Maybe I have to edit these lines of code:

var pieSeries = pieChart.series.push(new am4charts.PieSeries());
pieSeries.dataFields.value = "value";
pieSeries.dataFields.category = "category";
pieSeries.data = [{ value: 100, category: "First" }, { value: 20, category: "Second" }, { value: 10, category: "Third" }];

But How? I would like to pass the data as an array of a JSON, but the format is not a real problem.

Do you have any idea?

Thanke you.


Solution

  • you have info about the country on the hit event: event.target.dataItem.dataContext.id. The id field represents the country code.

    so you can use it in the showPieChart(polygon) function to retrieve specific data from the country code. you will get the country code in that function from polygon.dataItem.dataContext.id

    so, for example, build your data:

    let myData = {'ES': [{value: 51, category: 'first'}, {value: 99, category: 'second'}, { value: 4, category: "Third" }], 'FR': [{value: 80, category: 'first'}, {value: 20, category: 'second'}, { value: 23, category: "Third"}];
    

    and than, replace the dataItem.value = Math.round(Math.random() * 100); with:

    dataItem.value = myData[polygon.dataItem.dataContext.id][i].value;