0

I'm playing around with Javascript charts such an Amcharts and I want to be able to use external data I have saved locally.

How do I remove the information in the chart.data section so it reads data from a JSON file?

I tried using chart.datasource.url = "data.json"; but it didn't seem to work

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>amCharts V4 Example - simple-column-chart</title>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <div id="chartdiv"></div>
    <script src="../../../core.js"></script>
    <script src="../../../charts.js"></script>
    <script src="../../../themes/animated.js"></script>
    <script src="index.js"></script>
  </body>
</html>

Javascript

am4core.useTheme(am4themes_animated);

var chart = am4core.create("chartdiv", am4charts.XYChart);

chart.data = [{
    "country": "USA",
    "visits": 3025
}, {
    "country": "China",
    "visits": 1882
}, {
    "country": "Japan",
    "visits": 1809
}, {
    "country": "Germany",
    "visits": 1322
}, {
    "country": "UK",
    "visits": 1122
}, {
    "country": "France",
    "visits": 1114
}, {
    "country": "India",
    "visits": 984
}, {
    "country": "Spain",
    "visits": 711
}, {
    "country": "Netherlands",
    "visits": 665
}, {
    "country": "Russia",
    "visits": 580
}, {
    "country": "South Korea",
    "visits": 443
}, {
    "country": "Canada",
    "visits": 441
}];

chart.padding(40, 40, 40, 40);

var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.renderer.grid.template.location = 0;
categoryAxis.dataFields.category = "country";
categoryAxis.renderer.minGridDistance = 60;

var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.categoryX = "country";
series.dataFields.valueY = "visits";
series.tooltipText = "{valueY.value}"
series.columns.template.strokeOpacity = 0;

chart.cursor = new am4charts.XYCursor();

// as by default columns of the same series are of the same color, we add adapter which takes colors from chart.colors color set
series.columns.template.adapter.add("fill", function (fill, target) {
    return chart.colors.getIndex(target.dataItem.index);
});

Thanks in Advance

ARH94
  • 43
  • 6
  • 1
    Are you running this off of `file://`? [It needs to be on a web server](https://www.amcharts.com/docs/v4/concepts/data/loading-external-data/#Local_files) – xorspark Feb 27 '20 at 19:44
  • ah, how come? Is there a way around that? – ARH94 Feb 27 '20 at 19:47
  • 1
    Browser security restrictions - it says so right in the link. If you're running chrome, you can pass `--allow-file-access-from-files` as a command line argument but it's not recommended. – xorspark Feb 27 '20 at 20:04

0 Answers0