상세 컨텐츠

본문 제목

Google Charts

프로그래밍/스크립트

by 라제폰 2022. 12. 20. 15:17

본문

(function($w, root) {
    if (!!!$w) return;
    if (!!!$w[root]) return;

    const Base = $w[root];
    const Appl = Base.Core.namespace('pc');
    const Page = Base.Core.namespace('pc.sample.googleCharts');
    const Ctrl = Base.Control.Page.createControl(Page);

    Page.init	= function(oContext) {
        Ctrl.init(oContext);
        this.isInit = true;
        return this;
    };

    // Column Chart (google.visualization.ColumnChart)
    const columnChart = () => {
        const This = Ctrl;

        let dataTable = new google.visualization.DataTable();
        dataTable.addColumn('string', '집계일자');
        dataTable.addColumn({type: 'string', role: 'annotation'});
        dataTable.addColumn('number', '판매금액');
        dataTable.addColumn({type: 'number', role: 'annotation'});
        dataTable.addColumn({role: 'style'});

        dataTable.addRows([
            ['2023.05', '3등급',  13000000,   13000000,   'color: #999999'],
            ['2023.06', '1등급',  100000000,  100000000,  'color: #999999'],
            ['2023.07', '2등급',  50000000,   50000000,   'color: #999999'],
            ['2023.08', '1등급',  120000000,  120000000,  'color: #999999'],
            ['2023.09', '2등급',  50000000,   50000000,   'color: #999999'],
            ['2023.10', '1등급',  135000000,  135000000,  'color: #3498DB']
        ]);

        // 숫자 포맷
        let formatter = new google.visualization.NumberFormat({ pattern: '#,###원' });
        formatter.format(dataTable, 1);
        formatter.format(dataTable, 2);

        let options = {
            title: '판매등급 변동 추이',
            // subtitle: '판매금액 기준 최근 일주일', // 작동 안함
            //width: '100%',
            height: 500,
            chartArea: {
                top: 20,
                width: '80%',
                height: '80%'
            },
            vAxis: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 12,
                    color: '#999999'
                }
                //, format: '#,###만'
            },
            hAxis: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 12,
                    color: '#999999'
                }
            },
            tooltip: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 12,
                    color: '#212121'
                }
            },
            annotations: {
                alwaysOutside: true,
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 12,
                    color: '#999999'
                    //, auraColor: 'none'
                }
            },
            bar : {
                groupWidth : '20%' // 그래프 너비 설정 %
            },
            legend: { position: 'none' }
        };

        // google.charts.load "corechart" 패키지 사용시 google.visualization.ColumnChart 사용
        let chart = new google.visualization.ColumnChart(This.find('div[chart-id="columnChart"]'));
        chart.draw(dataTable, options);
    }

    // Column Chart (google.charts.Bar)
    const columnChartBar = () => {
        const This = Ctrl;

        let dataTable = new google.visualization.DataTable();
        dataTable.addColumn('string', '집계일자');
        dataTable.addColumn({type: 'string', role: 'annotation'});
        dataTable.addColumn('number', '판매금액');
        dataTable.addColumn({type: 'number', role: 'annotation'});
        dataTable.addColumn({role: 'style'});

        /* role 적용 안됨 */
        dataTable.addRows([
            ['2023.05', '3등급',  13000000,   13000000,   'color: #999999'],
            ['2023.06', '1등급',  100000000,  100000000,  'color: #999999'],
            ['2023.07', '2등급',  50000000,   50000000,   'color: #999999'],
            ['2023.08', '1등급',  120000000,  120000000,  'color: #999999'],
            ['2023.09', '2등급',  50000000,   50000000,   'color: #999999'],
            ['2023.10', '1등급',  135000000,  135000000,  'color: #3498DB']
        ]);

        // 숫자 포맷
        let formatter = new google.visualization.NumberFormat({ pattern: '#,###원' });
        formatter.format(dataTable, 1);
        formatter.format(dataTable, 2);

        let options = {
            chart: {
                title: '판매등급 변동 추이',
                subtitle: '판매금액 기준 최근 일주일' // subtitle 적용 안됨
            },
            bar : {
                groupWidth : '20%' // 그래프 너비 설정 %
            },
            bars: 'vertical',
            //width: '100%',
            height: 500,
            vAxis: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 20,
                    color: '#d95f02'
                },
                format: 'decimal'   // none, scientific, decimal, short
                //, format: '#,###만'
            },
            hAxis: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 15,
                    color: '#7570b3'
                }
            },
            colors: ['#1b9e77'/*, '#d95f02', '#7570b3'*/],
            legend: { position: 'none' },
            /* tooltip 적용 안됨 */
            // tooltip: {
            //     textStyle: {
            //         fontName: 'Noto Sans KR',
            //         fontSize: 12,
            //         color: '#212121'
            //     }
            // },
            // annotations: {
            //     alwaysOutside: true,
            //     textStyle: {
            //         fontName: 'Noto Sans KR',
            //         fontSize: 12,
            //         color: '#999999'
            //         //, auraColor: 'none'
            //     }
            // }
        };

        // google.charts.load "bar" 패키지 사용시 google.charts.Bar 사용
        let chart = new google.charts.Bar(This.find('div[chart-id="columnChartBar"]'));
        chart.draw(dataTable, google.charts.Bar.convertOptions(options));
    }

    // Column Chart
    const columnChart2 = () => {
        const This = Ctrl;

        let dataTable = new google.visualization.DataTable();
        dataTable.addColumn('timeofday', 'Time of Day');
        dataTable.addColumn('number', 'Motivation Level');
        dataTable.addColumn('number', 'Energy Level');

        dataTable.addRows([
            [{v: [8, 0, 0], f: '8 am'}, 1, .25],
            [{v: [9, 0, 0], f: '9 am'}, 2, .5],
            [{v: [10, 0, 0], f:'10 am'}, 3, 1],
            [{v: [11, 0, 0], f: '11 am'}, 4, 2.25],
            [{v: [12, 0, 0], f: '12 pm'}, 5, 2.25],
            [{v: [13, 0, 0], f: '1 pm'}, 6, 3],
            [{v: [14, 0, 0], f: '2 pm'}, 7, 4],
            [{v: [15, 0, 0], f: '3 pm'}, 8, 5.25],
            [{v: [16, 0, 0], f: '4 pm'}, 9, 7.5],
            [{v: [17, 0, 0], f: '5 pm'}, 10, 10],
        ]);

        let options = {
            title: 'Motivation and Energy Level Throughout the Day',
            hAxis: {
                title: 'Time of Day',
                format: 'h:mm a',
                viewWindow: {
                    min: [7, 30, 0],
                    max: [17, 30, 0]
                }
            },
            vAxis: {
                title: 'Rating (scale of 1-10)'
            },
            width: '100%',
            height: 500
        };

        // google.charts.load "bar" 패키지 사용시 google.charts.Bar 사용
        let chart = new google.charts.Bar(This.find('div[chart-id="columnChart2"]'));
        chart.draw(dataTable, options);
    }

    // Line Chart (google.visualization.LineChart)
    const lineChart = () => {
        const This = Ctrl;

        let dataTable = new google.visualization.DataTable();
        dataTable.addColumn('string', '날짜');
        dataTable.addColumn('number', '주문금액(취소주문 포함)');
        dataTable.addColumn('number', '취소금액(배송전 취소, 반품완료 주문금액)');

        dataTable.addRows([
            ['2022-11-01',  4320000,    230000],
            ['2022-11-02',  4320000,    210000],
            ['2022-11-03',  5320000,    130000],
            ['2022-11-05',  4320000,    200000],
            ['2022-11-06',  7320000,    230000],
            ['2022-11-07',  4320000,    200000],
            ['2022-11-08',  8320000,    930000],
            ['2022-11-09',  8320000,    200000],
            ['2022-11-10',  5320000,    400000],
            ['2022-11-11',  7320000,    500000],
            ['2022-11-12',  5320000,    300000],
            ['2022-11-13',  4320000,    200000],
            ['2022-11-14',  3320000,    400000]
        ]);

        // 숫자 포맷
        //let formatter = new google.visualization.NumberFormat({prefix: '$', suffix: '원', negativeColor: 'red', negativeParens: true});
        let formatter = new google.visualization.NumberFormat({ pattern: '#,###원' });
        formatter.format(dataTable, 1);
        formatter.format(dataTable, 2);

        let options = {
            title: '주문금액',
            subtitle: '최근 2주 실적',   // subtitle 작동 안함
            width: '100%',
            height: 500,
            colors: ['#F39C12', '#3498DB'], // HTML color string
            chartArea: {
                top: 20,
                width: '80%',
                height: '80%'
            },
            vAxis: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 10,
                    color: '#212121'
                }
                //, format: '#,###만'
            },
            hAxis: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 10,
                    color: '#999999'
                }
            },
            tooltip: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 10,
                    color: '#212121'
                },
                //trigger: 'selection',
                showColorCode: true
            },
            /* 범례 */
            legend: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 11,
                    color: '#212121'
                },
                position: 'bottom'
            },
            pointSize : 5,
            focusTarget: 'category'
        };

        // google.charts.load "corechart" 패키지 사용시 google.visualization.LineChart 사용
        let chart = new google.visualization.LineChart(This.find('div[chart-id="lineChart"]'));
        chart.draw(dataTable, options);
    }

    // Line Chart (google.charts.Line)
    const lineChartLine = () => {
        const This = Ctrl;

        let dataTable = new google.visualization.DataTable();
        dataTable.addColumn('string', '날짜');
        dataTable.addColumn('number', '주문금액(취소주문 포함)');
        dataTable.addColumn('number', '취소금액(배송전 취소, 반품완료 주문금액)');

        dataTable.addRows([
            ['2022-11-01',  4320000,    230000],
            ['2022-11-02',  4320000,    210000],
            ['2022-11-03',  5320000,    130000],
            ['2022-11-05',  4320000,    200000],
            ['2022-11-06',  7320000,    230000],
            ['2022-11-07',  4320000,    200000],
            ['2022-11-08',  8320000,    930000],
            ['2022-11-09',  8320000,    200000],
            ['2022-11-10',  5320000,    400000],
            ['2022-11-11',  7320000,    500000],
            ['2022-11-12',  5320000,    300000],
            ['2022-11-13',  4320000,    200000],
            ['2022-11-14',  3320000,    400000]
        ]);

        // 숫자 포맷
        //let formatter = new google.visualization.NumberFormat({prefix: '$', suffix: '원', negativeColor: 'red', negativeParens: true});
        let formatter = new google.visualization.NumberFormat({ pattern: '#,###원' });
        formatter.format(dataTable, 1);
        formatter.format(dataTable, 2);

        let options = {
            chart: {
                title: '주문금액',
                subtitle: '최근 2주 실적'
            },
            width: '100%',
            height: 500,
            colors: ['#F39C12', '#3498DB'], // HTML color string
            vAxis: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 10,
                    color: '#d95f02'
                }
                //, format: '#,###만'
            },
            hAxis: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 15,
                    color: '#7570b3'
                }
            },
            /* tooltip 작동 안함 */
            // tooltip: {
            //     textStyle: {
            //         fontName: 'Noto Sans KR',
            //         fontSize: 13,
            //         color: '#212121'
            //     },
            //     //trigger: 'selection',
            //     showColorCode: true
            // },
            /* 범례 */
            legend: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 20,
                    color: '#F39C12'
                },
                position: 'bottom'  // 작동 안함
            },
            //pointSize : 20, // 작동 안함
            //focusTarget: 'category' // 작동 안함
        };

        // google.charts.load "line" 패키지 사용시 google.charts.Line 사용
        let chart = new google.charts.Line(This.find('div[chart-id="lineChartLine"]'));
        chart.draw(dataTable, google.charts.Line.convertOptions(options));
    }

    // Donut Chart
    const donutChart = () => {
        const This = Ctrl;

        let dataTable = google.visualization.arrayToDataTable([
            ['취소사유', '취소건수'],
            ['단순변심(색상)',    11],
            ['단순변심(사이즈)',  8],
            ['단순변심(기타)',    3],
            ['배송지연',          5],
            ['컬러/사이즈 변경',  7],
            ['재주문',            7]
        ]);

        let options = {
            title: '취소 사유',
            //width: '100%',
            height: 500,
            pieHole: 0.4,
            //pieSliceBorderColor:'white',
            pieSliceText: 'percentage', // percentage, value, label, none
            chartArea: {
                top: 20,
                width: '80%',
                height: '80%'
            },
            pieSliceTextStyle: {
                fontName: 'Noto Sans KR',
                fontSize: 15,
                color: '#212121'
            },
            tooltip: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 12,
                    color: '#212121'
                },
                showColorCode: true
            },
            /* 범례 */
            legend: {
                textStyle: {
                    fontName: 'Noto Sans KR',
                    fontSize: 12,
                    color: '#212121'
                }
                , position: 'bottom'
            },
            slices: {
                0: {color: '#8D5BD3'},
                3: {color: '#E4D4FA'}
            }
        };

        let chart = new google.visualization.PieChart(This.find('div[chart-id="donutChart"]'));
        chart.draw(dataTable, options);
    }

    // Pie Chart
    const pieChart = () => {
        const This = Ctrl;

        let dataTable = google.visualization.arrayToDataTable([
            ['Task', 'Hours per Day'],
            ['Work',     11],
            ['Eat',      2],
            ['Commute',  2],
            ['Watch TV', 2],
            ['Sleep',    7]
        ]);

        let options = {
            title: 'My Daily Activities',
            width: '100%',
            height: 500,
        };

        let chart = new google.visualization.PieChart(This.find('div[chart-id="pieChart"]'));
        chart.draw(dataTable, options);
    }

    // 3D Pie Chart
    const pieChart3D = () => {
        const This = Ctrl;

        let dataTable = google.visualization.arrayToDataTable([
            ['Task', 'Hours per Day'],
            ['Work',     11],
            ['Eat',      2],
            ['Commute',  2],
            ['Watch TV', 2],
            ['Sleep',    7]
        ]);

        let options = {
            title: 'My Daily Activities',
            width: '100%',
            height: 500,
            is3D: true,
        };

        let chart = new google.visualization.PieChart(This.find('div[chart-id="pieChart3D"]'));
        chart.draw(dataTable, options);
    }

    /** Private page control overriding. */
    /** Page Control이 화면에 표시된 후 초기 작업을 재정의. */
    Ctrl.onLoadPanel = function() {
        if (!$w['overpass']) {throw new Error('There is no required grid generator.');}

        // corechart 사용
        google.charts.load('current', {packages:['corechart']});
        google.charts.setOnLoadCallback(columnChart);   // Column Chart

        // Material 베타 버전, corechart 패키지 대신 bar 패키지 사용
        // 개선된 색상 팔레트, 둥근 모서리, 명확한 레이블 형식, 시리즈 간의 더 엄격한 기본 간격, 부드러운 격자선 및 제목(자막 추가)을 포함하여 클래식 세로막대형 차트에 비해 많은 작은 개선점을 제공
        // 클래식 차트에서 사용할 수 있는 많은 옵션은 아직 제공되지 않습니다, 기존 옵션 중 하나를 사용하는 경우 convertOptions 사용해야 함
        google.charts.load('current', {'packages':['bar']});
        google.charts.setOnLoadCallback(columnChartBar);   // Column Chart

        google.charts.load('current', {'packages':['bar']});
        google.charts.setOnLoadCallback(columnChart2);   // Column Chart

        google.charts.load('current', {packages:['corechart']});
        google.charts.setOnLoadCallback(lineChart);     // Line Chart

        // Material 베타 버전, corechart 패키지 대신 line 패키지 사용
        google.charts.load('current', {'packages':['line']});
        google.charts.setOnLoadCallback(lineChartLine);     // Line Chart

        google.charts.load('current', {packages:['corechart']});
        google.charts.setOnLoadCallback(donutChart);    // Donut Chart

        //google.charts.load('current', {packages:['corechart']});
        google.charts.setOnLoadCallback(pieChart);    // Pie Chart

        //google.charts.load('current', {packages:['corechart']});
        google.charts.setOnLoadCallback(pieChart3D);    // 3D Pie Chart




    };



}) (window, __DOMAIN_NAME||'');

관련글 더보기