프로그래밍/JavaScript

구글차트(Google Chart) 사용해서 그래프 생성하기 - 라인차트, 컨트롤

dev109 2021. 1. 15.

목차

    반응형

    구글차트(Google Chart) 사용해서 그래프 생성하기 - 라인차트, 컨트롤

     

     

     

    구글차트(google-chart)의 line 그래프와 그래프에서 원하는 구간만 볼 수 있는 컨트롤바 생성 소스코드입니다.

    주제와 데이터는 임의로 지정하였으며, 원한다면 DB의 데이터를 사용할 수 있습니다.

     

     



    화면

     * 10월 14일자 데이터는 클릭했을 경우, 10월 23일자 데이터는 마우스 포인터를 올려놨을 경우에 나오는 툴팁입니다.

     * 그래프 아래에 컨트롤 바가 실제 그래프의 미니버전(?) 으로 출력됩니다. (사이즈 조절 가능, 다른 그래프로 대체 가능)

     

    구글차트(Google Chart) 사용해서 그래프 생성하기 - 라인차트, 컨트롤

     

     

    구글차트(Google Chart) 사용해서 그래프 생성하기 - 라인차트, 컨트롤

     

     

    GIF

     * 컨드롤바에서 그래프 중 구간(범위)을 선택하여 원하는 날짜의 그래프를 확대해서 볼 수 있습니다.

     * 화면 크기에 따라 그래프와 컨트롤바의 크기도 달라집니다.(반응형웹에서 사용가능)

    구글차트(Google Chart) 사용해서 그래프 생성하기 - 라인차트, 컨트롤

     

     


     

    첨부파일 & GitHub

     

    GoogleChart.zip
    다운로드

    GitHub    : https://github.com/89dev/JS-google_chart

    참조        : https://google-developers.appspot.com/chart/interactive/docs/gallery

     


     

    소스코드

    *html 한 페이지에 구성했습니다. (jsp파일에서도 당연히 사용 가능해요.)

     

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Line_Controls_Chart</title>
    
        <!-- jQuery -->
        <script src="https://code.jquery.com/jquery.min.js"></script>
        <!-- google charts -->
           <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
      </head>
      <body>
    
        <h4>사이트 방문자 성별 현황 그래프</h4>
    
        <div id="Line_Controls_Chart">
          <!-- 라인 차트 생성할 영역 -->
              <div id="lineChartArea" style="padding:0px 20px 0px 0px;"></div>
          <!-- 컨트롤바를 생성할 영역 -->
              <div id="controlsArea" style="padding:0px 20px 0px 0px;"></div>
            </div>
    
      </body>
    
      <script>
    
      var chartDrowFun = {
    
        chartDrow : function(){
            var chartData = '';
    
            //날짜형식 변경하고 싶으시면 이 부분 수정하세요.
            var chartDateformat     = 'yyyy년MM월dd일';
            //라인차트의 라인 수
            var chartLineCount    = 10;
            //컨트롤러 바 차트의 라인 수
            var controlLineCount    = 10;
    
    
            function drawDashboard() {
    
              var data = new google.visualization.DataTable();
              //그래프에 표시할 컬럼 추가
              data.addColumn('datetime' , '날짜');
              data.addColumn('number'   , '남성');
              data.addColumn('number'   , '여성');
              data.addColumn('number'   , '전체');
    
              //그래프에 표시할 데이터
              var dataRow = [];
    
              for(var i = 0; i <= 29; i++){ //랜덤 데이터 생성
                var total   = Math.floor(Math.random() * 300) + 1;
                var man     = Math.floor(Math.random() * total) + 1;
                var woman   = total - man;
    
                dataRow = [new Date('2017', '09', i , '10'), man, woman , total];
                data.addRow(dataRow);
              }
    
    
                var chart = new google.visualization.ChartWrapper({
                  chartType   : 'LineChart',
                  containerId : 'lineChartArea', //라인 차트 생성할 영역
                  options     : {
                                  isStacked   : 'percent',
                                  focusTarget : 'category',
                                  height          : 500,
                                  width              : '100%',
                                  legend          : { position: "top", textStyle: },
                                  pointSize        : 5,
                                  tooltip          : , showColorCode : true,trigger: 'both'},
                                  hAxis              : ,
                                                                      months: ,
                                                                      days  : ,
                                                                      hours : }
                                                                    },textStyle: },
                    vAxis              : ,gridlines:,textStyle:},
                    animation        : ,
                    annotations    : 
                                }
                  }
                });
    
                var control = new google.visualization.ControlWrapper({
                  controlType: 'ChartRangeFilter',
                  containerId: 'controlsArea',  //control bar를 생성할 영역
                  options: {
                      ui:{
                            chartType: 'LineChart',
                            chartOptions: {
                            chartArea: {'width': '60%','height' : 80},
                              hAxis: {'baselineColor': 'none', format: chartDateformat, textStyle: ,
                                gridlines:,
                                      months: ,
                                      days  : ,
                                      hours : }
                                }}
                            }
                      },
                        filterColumnIndex: 0
                    }
                });
    
                var date_formatter = new google.visualization.DateFormat({ pattern: chartDateformat});
                date_formatter.format(data, 0);
    
                var dashboard = new google.visualization.Dashboard(document.getElementById('Line_Controls_Chart'));
                window.addEventListener('resize', function() { dashboard.draw(data); }, false); //화면 크기에 따라 그래프 크기 변경
                dashboard.bind([control], [chart]);
                dashboard.draw(data);
    
            }
              google.charts.setOnLoadCallback(drawDashboard);
    
          }
        }
    
    $(document).ready(function(){
      google.charts.load('current', {'packages':['line','controls']});
      chartDrowFun.chartDrow(); //chartDrow() 실행
    });
      </script>
    </html>

     

     

     

     

    반응형

    댓글