기록하는 개발자

amCharts 5 계층형 Treemap 메뉴얼 본문

Open Source

amCharts 5 계층형 Treemap 메뉴얼

gitseok 2022. 11. 23. 18:14

amcharts5와 amcahrts4가 다른부분이 많고 상세한 부분은 설명이 되어있지 않아(무료버전) 어려움을 겪었습니다.

이 글을 보는분들께 도움이 되었으면 좋겠습니다.


구현 사항

· amcharts5 설정

· root, container

     · 기본 세팅 및 하위 기능 반영

· series 

     · 데이터 변수

     · 배경 색상

     · 워터마크

     · 툴팁

· myTheme

     · 기타


 - amcharts5 설정

1. amCharts5 다운로드 및 적용

 

Download amCharts 5 - amCharts

Install via NPM Latest version () The best way to get amCharts 5 is via NPM. The charting functionality is in the package @amcharts/amcharts5. Map files are in @amcharts/amcharts5-geodata. Font files used for PDF in @amcharts/amcharts5-fonts. Use CDN Lat

www.amcharts.com

//다운로드O
<script src="상위 경로/amcharts5/index.js"></script>
<script src="상위 경로/amcharts5/hierarchy.js"></script>
<script src="상위 경로/amcharts5/themes/Animated.js"></script>
//다운로드x
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/hierarchy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js">

2. div 생성

<div id="treemap-chart" style="height:600px; width:1000px;"></div>

 - root, container

  <script type="text/javascript">

        $(function () {
            treeChartCreate();
        });
        function treeChartCreate() {

            var root = am5.Root.new("treemap-chart"); //div 연동

            root.setThemes([
                am5themes_Animated.new(root),
            ]);

            var container = root.container.children.push(
                am5.Container.new(root, {
                    //div 영역의 사용할 비율(%) 지정
                    width: am5.percent(100), 
                    height: am5.percent(100),
                    layout: root.verticalLayout
                })
            );
            //**이후 코드들은 이곳에 추가됩니다.
        }
        
  </script>

 - series

           // series 설정
            var series = container.children.push(
                am5hierarchy.Treemap.new(root, {
                    sort: "descending",         //정렬 기준 ["ascending"| "descending"|"none"] (기본값)
                    singleBranchOnly: true,    //If set to true will make all other branches collapse when some branch is expanded.
                    downDepth: 1,               //노드 선택시 열리는 하위 데이터 기준
                    upDepth: 0,                 //현재 노드에서 표시할 상위 노드의 값 깊이
                    initialDepth: 1,            //초기에 표시할 노드의 깊이
                    valueField: "value",        //차트의 크기를 정할 데이터가 변수 지정
                    categoryField: "name",      //카테고리 변수 지정
                    childDataField: "children", //자식 요소 변수 지정
                    layoutAlgorithm: "binary",  //트리맵 알고리즘 설정
                    nodePaddingOuter: 0,        //밖의 간격 조정
                    nodePaddingInner: 0,        //안의 간격 조정
                    fillField: 'color',         //색상을 지정할 변수 지정
                })
            );
            
            /*
            배경색 지정
            *** 사용하시려면 하단의 series.data.setAll 부분에 color : "#FFFFFF" 형식으로 색상을 추가해야합니다.
            */
            series.rectangles.template.adapters.add("fill", function (fill, target) {
                var customColor = target.dataItem.dataContext.color;
                return customColor || fill;
            });

            /*
            워터마크 추가
            */
            series.bullets.push(function (root, series, dataItem) {
                var depth = dataItem.get("depth");      //depth 가져옴
                var logo = dataItem.dataContext.logo;   //logo 변수에 지정된 내용 불러오기

                if (depth == 1) {
                    var picture = am5.Picture.new(root, {
                        //이미지 경로
                        src: "./resources/images/treemap/" + logo + ".png",
                        //위치 지정
                        centerX: am5.p50,
                        centerY: am5.p50,
                        //크기 지정
                        width: am5.percent(50),
                        maxHeight: am5.percent(90),
                        isMeasured: true,
                        opacity: 0.2, //기본 투명도
                    });

                    picture.states.lookup("default").setAll({ opacity: 0.2 }); //해당 depth 이동시 투명도 
                    return am5.Bullet.new(root, { sprite: picture });
                }

                if (depth == 2) {
                    var picture = am5.Picture.new(root, {
                        //이미지 경로
                        src: "./resources/images/treemap/" + logo + ".png",
                        //위치 지정
                        centerX: am5.p50,
                        centerY: am5.p50,
                        //크기 지정
                        width: am5.percent(50),
                        maxHeight: am5.percent(90),
                        isMeasured: true,
                        opacity: 0.2 //기본 투명도
                    });

                    picture.states.lookup("default").setAll({ opacity: 0.2 }); //해당 depth 이동시 투명도 
                    return am5.Bullet.new(root, {sprite: picture });
                }

            });
            /*
            툴팁(마우스 오버시 나오는 텍스트)
            */
            var tooltip = am5.Tooltip.new(root, {
                autoTextColor: false, //자동 색상 지정 false
                getFillFromSprite: false,
                labelText: "[bold]{name}\n는 " //툴팁 내용
            });
            //툴팁 배경
            tooltip.get("background").setAll({
                fill: am5.color(0xffffff),
                fillOpacity: 0.8
            });
            //툴팁 글씨 생상
            tooltip.label.setAll({
                //fill: "#4682B4",
                fill: "#000000",
            });
            series.set("tooltip", tooltip);

           
            /*
            라벨(필드에 나타나는 텍스트)
            []태그를 활용해 bold, fontSize 설정 가능
            [/] 뒤 부터는 기본 폰트로 초기화
            */
            series.labels.template.setAll({
                text: "[bold;fontSize:25px;]{name}[/]"
			+"{date}"
			+"{designer}"
            });

            container.children.moveValue(
                am5hierarchy.BreadcrumbBar.new(root, {
                    series: series
                }), 0
            );

            //데이터 세팅
            series.data.setAll([{
                name: "gitseok",
                children: [
                    {
                        name: '프론트엔드',
                        logo : "front",
                        children: [
                            {
                                name: "HTML",
                                value: 72,
                                date: '[fontSize:20px]\n\n출시일 : 1993.1.1',
                                designer: '[fontSize:20px]\n설계자 : Tim Berners-Lee',
                                logo: "html",
                            },
                            {
                                name: "CSS",
                                value: 34,
                                date: '[fontSize:20px]\n\n출시일 : 1996.12.17',
                                designer: '[fontSize:20px]\n설계자 : Håkon Wium Lie',
                                logo: "css",
                            },
                            {
                                name: "Javascript",
                                value: 94,
                                date: '[fontSize:20px]\n\n출시일 : 1995.12.4',
                                designer: '[fontSize:20px]\n설계자 : Brendan Eich',
                                logo: "js",
                            },

                        ],
                    },
                    {
                        name: '백엔드',
                        logo: "back",
                        children: [
                            {
                                name: "PHP",
                                value: 25,
                                date: '[fontSize:20px]\n\n출시일 : 1991.2.20',
                                designer: '[fontSize:20px]\n설계자 : Rasmus Lerdorf',
                                logo: "php",
                            },
                            {
                                name: "Node.js",
                                value: 24,
                                date: '[fontSize:20px]\n\n출시일 : 2009.5.27',
                                designer: '[fontSize:20px]\n설계자 : Ryan Dahl',
                                logo: "nodejs",
                            },
                            {
                                name: "JavaScript",
                                value: 36,
                                date: '[fontSize:20px]\n\n출시일 : 1995.12.4',
                                designer: '[fontSize:20px]\n설계자 : Brendan Eich',
                                logo: "js",
                            },
                            {
                                name: "C++",
                                value: 9,
                                date: '[fontSize:20px]\n\n출시일 : 1985.1.1',
                                designer: '[fontSize:20px]\n설계자 : Bjarne Stroustrup',
                                logo: "c++",
                            },
                            {
                                name: "C",
                                value: 15,
                                date: '[fontSize:20px]\n\n출시일 : 1972.1.1',
                                designer: '[fontSize:20px]\n설계자 : Dennis MacAlistair Ritchi',
                                logo: "c",
                            },
                            {
                                name: "Java",
                                value: 12,
                                date: '[fontSize:20px]\n\n출시일 : 1995.1.1',
                                designer: '[fontSize:20px]\n설계자 : James Gosling',
                                logo: "java",
                            },
                            {
                                name: "Python",
                                value: 17,
                                date: '[fontSize:20px]\n\n출시일 : 1991.2.20',
                                designer: '[fontSize:20px]\n설계자 : Guido van Rossum',
                                logo: "python",
                            },
                        ],

                    }
                ]
            }]);

 - myTheme

찾았지만 사용하지 않은 기능들이 많습니다.

테스트결과 트리맵 데이터의 깊이(depth) 기준으로  설정이 대부분 가능해서 상황에따라 유용하게 사용할 수 있을 것 같습니다.

  const myTheme = am5.Theme.new(root);
			//strokeWidth : 선의 굵기
			//strokeOpacity : 배경 투명도
			// depth 가 1인 대상
			myTheme.rule("RoundedRectangle", ["hierarchy", "node", "shape", "depth1"]).setAll({
			  strokeWidth: 2, //선 굵기
			});
            // depth 가 2인 대상
			myTheme.rule("RoundedRectangle", ["hierarchy", "node", "shape", "depth2"]).setAll({
			  strokeWidth: 1,
			  strokeOpacity: 1 
			});

			//라벨 설정(폰트 사이즈, 배경 색상 등 수정가능) *내용 변경은 불가능
			/*
			myTheme.rule("Label").setAll({
				//fontSize : 20,
				//fill: am5.color(0x777777)
				});
			//depth : 1 대상
			myTheme.rule("Label", ["node", "depth1"]).setAll({
			forceHidden: true,
			});
			//depth : 2 대상
			myTheme.rule("Label", ["node", "depth2"]).setAll({
			  fontSize: 10
			});
			*/
			// root에 Theme 적용
            root.setThemes([
                myTheme
            ]);

실행 결과

실행 결과

참고 사이트

예제사이트

- amchart5 GitHub

- amchart4 GitHub

- 워터마크 참고

- 글자 색상 변경

- 배경 색상 개별 적용 1

- 배경 색상 개별 적용 2

 

 

개인적으로 정리한 내용을 간단하게 풀어 작성했습니다.
이해가 안가는 부분은 댓글 남겨주시면 설명해드리겠습니다.

'Open Source' 카테고리의 다른 글

MyBatis resultMap collection 사용법 [1:N select]  (0) 2022.07.29
summernote 메뉴얼  (0) 2021.12.05
CKEditor5 메뉴얼  (0) 2021.12.05
Docker 설정 메뉴얼  (0) 2021.12.05
Comments