sue
  • amCharts5 튜토리얼
    2022년 06월 08일 23시 32분 44초에 업로드 된 글입니다.
    작성자: sue24

    세계지도를 활용한 프로젝트를 만들기 위해서 amCharts5를 사용했다.

    https://www.amcharts.com/docs/v5/getting-started/

    1. install

      npm install @amcharts/amcharts5

      import * as am5 from "@amcharts/amcharts5";
      import * as am5xy from "@amcharts/amcharts5/xy";
    1. cdn

      <script src="https://cdn.amcharts.com/lib/5/index.js"></script>
      <script src="https://cdn.amcharts.com/lib/5/xy.js"></script>

    root element

    차트를 만들 때 가장 중요한 오브젝트

    wrapper같은 느낌

    var root = am5.Root.new("chartdiv");

    Root 인스턴스가 new()가 아니라(class' static method)

    new [ClassName]을 사용했다

    amCharts5는 모두 이 방식을 사용할 것이다

    이 때 넘기는 인자는 id다(참조 방식도 가능)

    html에 chartdiv를 id로 하는 div가 있어야한다(높이, 너비 설정도 잊지 말자)

    DOM이 완전히 로드되기 전에 코드가 실행되서 아직 div#chartdiv가 없는데

    root를 만들려고 하면 에러가 난다.

    그럴 때를 대비해서

    am5.ready(function() {
      var root = am5.Root.new("chartdiv");
    });
    • formatters

      출력할 텍스트에 관련한 전반적인 규칙

      formatters are not inheritable(부모가 local formatter 갖고 있어도 자식은 global)

      • numberFormatter
      • dateFormatter
      • durationFormatter

      global formatter

      root.numberFormatter.set("numberFormat", "#,###.00");

      local formatter(엘리먼트 수준, 첫글자가 대문자)

      yAxis.set("numberFormatter", am5.NumberFormatter.new(root, {
        "numberFormat": "#,###.00"
      }));
    • performance

      the smaller the fps number(frames per second), the less resources charts will use, at the expense of smoothness of animations

      root.fps = 30;

    • time zone

      보통 사용자의 로컬 타임존

      특정하고 싶다면...

      root.timezone = am5.Timezone.new("America/Vancouver");

      "UTC", "Asia/Tokyo", "Europe/Lisbon"

    • setting

      new() call의 두번째 인자로 세팅 오브젝트를 넘길 수 있다

      var root = am5.Root.new("chartdiv", {
        useSafeResolution: false
      })

      useSafeResolution: 주어진 장치에서 안전한 해상도를 자동으로 선택하겠다

    • reusing

      차트는 날려버리되 루트는 남겨서 새로운 차트를 만들고 싶을 때,

      root.container.children.clear();

      아예 없애고 새 엘리먼트 만드는 것보다 빠르다

      기존에 만든 루트 엘리먼트를 참조하고 있는 것이 없다면

      am5.registry.rootElements에서 찾을 수 있다

      am5.array.each(am5.registry.rootElements, function(root) {
        if (root.dom.id == divId) {
          root.dispose();
        }
      });
    • disposing

      root.dispose();

      chart를 처리하는 것만으로는 부족하고 root 수준에서 끝내야한다.

      dispose하기 전에 동일한 div에 새로운 root를 만들려고 하면 에러가 난다

    • auto-resize

      root.autoResize = false;

      부모 div의 사이즈에 자동으로 맞춘다

      false로 하면 부모의 사이즈 변경과 상관 없이 처음 사이즈로 남는다

      직접 resize 작업을 할 수도 있다.

      root.resize();

    • chart ready event

      차트가 준비되었고 모든 기초 애니메이션이 끝난 것을 알고 싶다면

      frameended이벤트를 이용할 수 있다.

      var timeout;
      
      root.events.on("frameended", exportChart);
      
      function exportChart() {
        if (timeout) {
          clearTimeout(timeout);
        }
        timeout = setTimeout(function() {
          root.events.off("frameended", exportChart);
          console.log("Chart ready!");
        }, 100)
      }

      차트의 내용에 업데이트가 있으면 루트의 frameended이벤트가 만들어진다

    chart elements

    root에 chart instance, labels, containers, legends같은 것을 설정해보자

    여기서는 파이차트를 만들어본다

    start에서 삽입한 cdn은 코어만 가지고 있어서

    파이차트를 그리려면 percent 모듈이 필요하다

    <script src="https://cdn.amcharts.com/lib/5/percent.js"></script>

    percent.js이므로 percent 모듈에서 오는 것은 am5percent.으로 시작한다

    // good to reuse
    var chart = root.container.children.push(
      am5percent.PieChart.new(
        root, {}
      )
    );
    
    // another way
    var chart = am5percent.PieChart.new(root, {});
    root.container.children.push(chart);

    root 엘리먼트가 아니라면 new()의 첫번째 인자는 root 인스턴스여야 한다.

    key-value 오브젝트가 새로 만들어지는 오브젝트의 세팅을 맡는다

    여기서는 빈 오브젝트를 넘겨서 파이차트의 세팅을 하지 않았다.

    var series = chart.series.push(
        am5percent.PieSeires.new(
          root, {
          valueField: "value",
          categoryField: "category"
        }
      )
    );
    
    // another way
    var series = chart.series.push(
        am5percent.PieSeries.new(root, {})
    );
    series.set("valueField", "value");
    series.set("categoryField", "category");
    
    // another way to set multiple setting
    var series = chart.series.push(
        am5percent.PieSeries.new(root, {})
    );
    series.setAll({
      valueField: "value",
      categoryField: "category"
    });
    

    파이시리즈에서는 세팅을 해 줘야한다.

    데이터 삽입하기

    amCharts5에서 데이터는 오브젝트에서 바로 세팅된다

    데이터를 사용하는 오브젝트는 data라는 속성이 존재한다.

    data는 데이터를 공급하는 오브젝트다

    series.data.setAll([{
      category: "Research",
      value: 1000
    }, {
      category: "Marketing",
      value: 1200
    }, {
      category: "Sales",
      value: 850
    }]);

    데이터 세팅은 가능한 마지막에 이루어지게 해야 한다.

    데이터가 세팅되면 관련 오브젝트들이 모두 생성되기 때문에,

    이후에 적용하는 설정은 적용되지 않을 수도 있다

    pieChart img

    hover하면 툴팁도 나온다

    pieChart hover img

    'JS' 카테고리의 다른 글

    amCharts5 지도 줌, overlay  (0) 2022.06.10
    amCharts5 세계 지도 - 나라별  (0) 2022.06.09
    함수도 오브젝트!  (0) 2020.11.03
    Objects and the dot  (0) 2020.08.25
    연산자의 우선순위와 결합법칙  (0) 2020.08.21
    댓글