반응형

Apache Echarts

웹이나 앱기반 애플리케이션 개발 시 시각화 차트 구현시 무료이면서 괜찮은 라이브러리 Apache ECharts에 대해 설명드리고 javascript 기반 간단하게 적용하는 방법을 예제를 통해 구현해 보겠습니다.

 

Apache ECharts 장단점

제가 생각하는 Apache ECharts 최대 장점은 무료이면서 기본 차트부터 3D, 지도(Map) 차트등 다양한 차트를 지원합니다. Apache 프로젝트 이기 때문에 설명이나 예제(데모)가 다양하고 쉽게 적용 가능합니다. 또한 Dark 등 쉽게 테마를 적용 가능합니다.

Apache ECharts는 사용자가 웹 애플리케이션을 위한 대화형 차트 및 시각화를 생성할 수 있는 오픈 소스 JavaScript 시각화 라이브러리입니다. 다음은 ECharts 사용의 장단점입니다.

장점:

1. 다양한 차트 유형: ECharts는 라인 차트, 막대 차트, 산점도, 파이 차트 등 다양한 차트 유형을 지원합니다.
2. 사용자 지정 가능: ECharts는 색 구성표, 스타일 및 데이터 형식을 포함하여 다양한 사용자 지정 옵션을 제공합니다.
3. 대화형: ECharts는 확대/축소, 데이터 강조 표시 및 데이터 필터링을 포함하여 손쉬운 상호 작용을 허용합니다.
4. 쉬운 통합: ECharts는 React, Angular 및 Vue와 같은 다른 JavaScript 프레임워크와 쉽게 통합될 수 있습니다.
5. 교차 플랫폼: ECharts는 데스크탑과 모바일 장치 모두에서 사용할 수 있습니다.
6. 활동적인 커뮤니티: ECharts에는 정기적인 업데이트와 새로운 기능이 추가되는 크고 활동적인 커뮤니티가 있습니다.

단점:

1. 학습 곡선: ECharts는 광범위한 기능과 사용자 정의 옵션으로 인해 다른 시각화 라이브러리보다 학습 곡선이 더 가파릅니다.
2. 제한된 문서: ECharts에는 많은 문서가 있지만 라이브러리의 일부 영역에는 자세한 설명이나 예제가 부족할 수 있습니다.
3. 성능 문제: ECharts는 대규모 데이터 세트 또는 복잡한 시각화로 인해 성능 문제가 발생할 수 있습니다.
4. 제한된 내보내기 옵션: ECharts는 현재 차트 내보내기를 이미지 또는 SVG 파일로만 지원합니다.

전반적으로 ECharts는 광범위한 사용자 지정 옵션과 상호 작용을 제공하는 강력하고 다재다능한 시각화 라이브러리입니다. 그러나 대규모 데이터 세트 및 복잡한 시각화를 학습하고 최적화하려면 약간의 추가 노력이 필요할 수 있습니다.

 

Apache ECharts 시작하기

 

Apache ECharts 데모

[백문이 불여일견] 어떤 차트들이 있는지 데모(Examples)를 먼저 보시고 원하는 차트를 선택하고 적용하시면 됩니다.

 

Apache ECharts Get Started

Get Started 페이지에 설명이 되어 있는데 간단한 차트는 Html을 만들고 echarts.js만 Inclued만 하면 된다고 합니다.

 

Getting Apache ECharts (echarts.js 다운로드하기)

echarts.js파일은  https://www.jsdelivr.com/package/npm/echarts select dist/echarts.js, click and save it as echarts.js file.] 

echarts.js 파일 아래에 첨부하였습니다.

echarts.js
3.27MB

 

Including ECharts (echarts.js inclued 하기)

 

Create a new index.html file in the directory where you just saved echarts.js, with the following content:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <!-- Include the ECharts file you just downloaded -->
    <script src="echarts.js"></script>
  </head>
</html>
 

When you open this index.html, you will see an empty page. But don't worry. Open the console and make sure that no error message is reported, then you can proceed to the next step.

 

Plotting a Simple Chart (Chart가 그려질 DOM container div를 선언한다)

Before drawing we need to prepare a DOM container for ECharts with a defined height and width. Add the following code after the </head> tag introduced earlier.

<body>
  <!-- Prepare a DOM with a defined width and height for ECharts -->
  <div id="main" style="width: 600px;height:400px;"></div>
</body>

 

 

ECharts 구현 적용 순서

 

1. echarts.js 등록
2. 차트 위치  지정(div , DOM Container 위치)
3. myChart 선언
4. options 지정    > title : 차트 Title
   > legend : 범례 지정
   > xAxis : 가로 x 축 지정
   > yAxis : 세로 y축 지정
   > series : 그래프 데이터 

 

▼ Sample

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>ECharts</title>
    <!-- Include the ECharts file you just downloaded -->
    <script src="echarts.js"></script>
  </head>
  <body>
    <!-- Prepare a DOM with a defined width and height for ECharts -->
    <div id="main" style="width: 600px;height:400px;"></div>
    <script type="text/javascript">
      // Initialize the echarts instance based on the prepared dom
      var myChart = echarts.init(document.getElementById('main'));

      // Specify the configuration items and data for the chart
      var option = {
        title: {
          text: 'ECharts Getting Started Example'
        },
        tooltip: {},
        legend: {
          data: ['sales']
        },
        xAxis: {
          data: ['Shirts', 'Cardigans', 'Chiffons', 'Pants', 'Heels', 'Socks']
        },
        yAxis: {},
        series: [
          {
            name: 'sales',
            type: 'bar',
            data: [5, 20, 36, 10, 10, 20]
          }
        ]
      };

      // Display the chart using the configuration items and data just specified.
      myChart.setOption(option);
    </script>
  </body>
</html>

 

 

Apache ECharts 예제 중 Stacked Line 적용 실습

 

 데모 소스 가져오기

Examples 차트에서 원하는 차트를 선택합니다.

② [Full Code] Tab을 클릭합니다.

③ 테마를 지정합니다. [ 예제로 다크 모드를 선택하였습니다.]

④ var chartDom 부분부터 아래까지 쭈욱 코드를 복사합니다.

Apache ECharts 소스 가져오기

 

▼ 하단의 [Download] 버튼을 클릭하면 Html 소스로 받을수 있습니다.

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>ECharts</title>
    <!-- Include the ECharts file you just downloaded -->
    <script src="echarts.js"></script>
  </head>
  <body>
    <!-- Prepare a DOM with a defined width and height for ECharts -->
    <div id="main" style="width: 800px;height:600px;"></div>
    <script type="text/javascript">
        var chartDom = document.getElementById('main');
        var myChart = echarts.init(chartDom, 'dark');
        var option;

        option = {
        title: {
            text: 'Stacked Line'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        toolbox: {
            feature: {
            saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
            name: 'Email',
            type: 'line',
            stack: 'Total',
            data: [120, 132, 101, 134, 90, 230, 210]
            },
            {
            name: 'Union Ads',
            type: 'line',
            stack: 'Total',
            data: [220, 182, 191, 234, 290, 330, 310]
            },
            {
            name: 'Video Ads',
            type: 'line',
            stack: 'Total',
            data: [150, 232, 201, 154, 190, 330, 410]
            },
            {
            name: 'Direct',
            type: 'line',
            stack: 'Total',
            data: [320, 332, 301, 334, 390, 330, 320]
            },
            {
            name: 'Search Engine',
            type: 'line',
            stack: 'Total',
            data: [820, 932, 901, 934, 1290, 1330, 1320]
            }
        ]
        };

        option && myChart.setOption(option);
    </script>
  </body>
</html>

 

이렇게 몇 분 만에 기본 소스를 만들 수 있고요 데이터 부분과 legend , x축, y축 정보만 맞추면 되겠습니다.

추가로 2초마다( 그래프를 새로 그리고

    <script type="text/javascript">
        let interval = setInterval(function(){
            drawChart();
        }, 2000);
    </script>

데이터는 Random 하게 가져오는 부분을 추가하여

    <script type="text/javascript">
        function getRandom(maxLimit = 100){
            let rand = Math.random() * maxLimit;
            rand = Math.floor(rand);
            return rand;
        }
    </script>

동적으로 그래프가 변하도록 소스 추가 하였습니다.

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>ECharts</title>
    <!-- Include the ECharts file you just downloaded -->
    <script src="echarts.js"></script>
  </head>
  <body>
    <!-- Prepare a DOM with a defined width and height for ECharts -->
    <div id="main" style="width: 800px;height:600px;"></div>
    <script type="text/javascript">
        let interval = setInterval(function(){
            drawChart();
        }, 2000);
    </script>
    <script type="text/javascript">
        function drawChart(){
            // Initialize the echarts instance based on the prepared dom
                var chartDom = document.getElementById('main');
                var myChart = echarts.init(chartDom, 'dark');
                var option;

                myChart.clear();

                option = {
                title: {
                    text: 'Stacked Line'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                    saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                    name: 'Email',
                    type: 'line',
                    stack: 'Total',
                    // data: [120, 132, 101, 134, 90, 230, 210]
                    data:  [
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                        ]
                    },
                    {
                    name: 'Union Ads',
                    type: 'line',
                    stack: 'Total',
                    // data: [220, 182, 191, 234, 290, 330, 310]
                    data:  [
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                        ]                   
                    },
                    {
                    name: 'Video Ads',
                    type: 'line',
                    stack: 'Total',
                    // data: [150, 232, 201, 154, 190, 330, 410]
                    data:  [
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                        ]  
                    },
                    {
                    name: 'Direct',
                    type: 'line',
                    stack: 'Total',
                    // data: [320, 332, 301, 334, 390, 330, 320]
                    data:  [
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                        ]  
                    },
                    {
                    name: 'Search Engine',
                    type: 'line',
                    stack: 'Total',
                    // data: [820, 932, 901, 934, 1290, 1330, 1320]
                    data:  [
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                                getRandom(500),
                        ]  
                    }
                ]
                };

                option && myChart.setOption(option);
        }
    </script>
    <script type="text/javascript">
        function getRandom(maxLimit = 100){
            let rand = Math.random() * maxLimit;
            rand = Math.floor(rand);
            return rand;
        }
    </script>
  </body>
</html>
반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기