티스토리 뷰

단순히 Array형식의 데이터를 가지고 chart를 그리는 것은 어렵지 않았다.
하지만 실제로 UI에 적용해 두니, 데이터가 많아진다면(즉, line chart라면 차트에 선이 많아진다면?) 사용자가 보기 불편해 하지 않을까 라는 생각이 들었다.
그래서 사용자가 선택한 항목만 선으로 그려 줄 순 없을까? 라는 궁금증이 들었다.

무작정 진행해보기.
Google에서 검색을 해보니(api reference만 잘 읽어봐도 금방 찾는데 ㅠ) 많은 정보들이 있었다.
그 중 Data Format인 DataTable이 아니라 DataView를 사용해서 어렵지 않게 구현할 수 있었다.


Api Reference를 살펴보면 DataView라는 것이 있는 것을 확인할 수 있다.

사용법은 간단하다. DataTable 객체를 전과 동일하게 생성하고, DataView 생성시 생성자 parameter로 주면 된다.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Employee Name');
data.addColumn('date', 'Start Date');
data.addRows(6);
data.setCell(0, 0, 'Mike');
data.setCell(0, 1, new Date(2008, 1, 28));
data.setCell(1, 0, 'Bob');
data.setCell(1, 1, new Date(2007, 5, 1));
data.setCell(2, 0, 'Alice');
data.setCell(2, 1, new Date(2006, 7, 16));
data.setCell(3, 0, 'Frank');
data.setCell(3, 1, new Date(2007, 11, 28));
data.setCell(4, 0, 'Floyd');
data.setCell(4, 1, new Date(2005, 3, 13));
data.setCell(5, 0, 'Fritz');
data.setCell(5, 1, new Date(2007, 9, 2));

// Create a view that shows everyone hired since 2007.
var view = new google.visualization.DataView(data);
view.setRows(view.getFilteredRows([{column: 1, minValue: new Date(2007, 0, 1)}]));
var table = new google.visualization.Table(document.getElementById('test_dataview'));
table.draw(view, {sortColumn: 1});
여기서 setCell() 을 통해서 데이터를 구성할 때, 첫 번째 parameter인 column index를 통해서 control을 할 수 있다.(물론 columne 뿐만 아니라 row도 control할 수 있다. 여기서는 column만 구현해본다.)
chart를 그리기 전에 view.setColumns(columnIndexs) 를 통해서 일부 컬럼만 chart에 그리도록 할 수 있다.

sample 에 적용해 보면,
// Create a view that shows everyone hired since 2007.
var view = new google.visualization.DataView(data);
view.setColumns([0,1,2,3,4]);
var table = new google.visualization.Table(document.getElementById('test_dataview'));
table.draw(view, {sortColumn: 1});
위 처럼 0, 1, 2, 3, 4번 index를 array형식으로 전달하면 data 중 5번을 제외한 나머지만 화면에 그려지게 된다. 즉, 0, 1, 2, 3, 4 번 index data만 화면에 그려지게 되는 것이다.
그려지기 바라는 데이터의 index를 설정함으로서 일부만 그려지게도 할 수 있지만, 반대로 일부 column을 숨길 수도 있다.
// Create a view that shows everyone hired since 2007.
var view = new google.visualization.DataView(data);
view.hideColumns([5]);
var table = new google.visualization.Table(document.getElementById('test_dataview'));
table.draw(view, {sortColumn: 1});
위 두 sample 코드는 같은 역할을 한다.

hideColumns(columnIndexes) none

Hides the specified columns from the current view. columnIndexes is an array of numbers representing the indexes of the columns to hide. These indexes are the index numbers in theunderlying table/view. The numbers in columnIndexes do not have to be in order (that is, [3,4,1] is fine). The remaining columns retain their index order when you iterate through them. Entering an index number for a column already hidden is not an error, but entering an index that does not exist in the underlying table/view will throw an error. To unhide columns, callsetColumns().

Example: If you have a table with 10 columns, and you call setColumns([2,7,1,7,9]), and then hideColumns([7,9]), the columns in the view will then be [2,1].

setColumns(columnIndexes) None

Specifies which columns are visible in this view. Any columns not specified will be hidden. This is an array of column indexes in the underlying table/view, or calculated columns. If you don't call this method, the default is to show all columns. The array can also contain duplicates, to show the same column multiple times. Columns will be shown in the order specified.

  • columnIndexes - An array of numbers and/or objects (can be mixed):
    • Numbers specify the index of the source data column to include in the view. The data is brought through unmodified. If you need to explicitly define a role or additional column properties, specify an object with a sourceColumn property.
    • Objects specify a calculated column. A calculated column creates a value on the fly for each row and adds it to the view. The object must have the following properties:
      • calc [function] - A function that will be called for each row in the column to calculate a value for that cell. The function signature is func(dataTable,row), where dataTable is the source DataTable, and row is the index of the source data row. The function should return a single value of the type specified by type.
      • type [string] - The JavaScript type of the value that the calc function returns.
      • label [Optionalstring] - An optional label to assign to this generated column. If not specified, the view column will have no label.
      • id [Optionalstring] - An optional ID to assign to this generated column.
      • sourceColumn - [Optionalnumber] The source column to use as a value; if specified, do not specify the calc or the type property. This is similar to passing in a number instead of an object, but enables you to specify a role and properties for the new column.
      • properties [Optionalobject] - An object containing any arbitrary properties to assign to this column. If not specified, the view column will have no properties.
      • role [Optionalstring] - A role to assign to this column. If not specified, the existing role will not be imported.

Examples:

// Show some columns directly from the underlying data.
// Shows column 3 twice.
view.setColumns([3, 4, 3, 2]);

// Underlying table has a column specifying a value in centimeters.
// The view imports this directly, and creates a calculated column
// that converts the value into inches.
view.setColumns([1,{calc:cmToInches, type:'number', label:'Height in Inches'}]);
function cmToInches(dataTable, rowNum){
  return Math.floor(dataTable.getValue(rowNum, 1) / 2.54);
}
이를 응용하여 사용자가 선택한 일부의 데이터만 화면에 그려줄 수 있다.

아래 코드는 실제 서비스에 한 번 적용해 본 간단한 코드이다.
function drawChart() {
    var view = new google.visualization.DataView(getDataTable());
    var columnArrays = getIndicatorTypeArray();
    if (columnArrays != null) {
        view.setColumns(columnArrays);
    }

    var options = {
        title: '일별 지표',
        legend: {position: 'top', textStyle: {fontSize: 12}, maxLines:3},
        hAxis: {baseline: 'discrete', direction: 1, format: '#,###'},
        height: 700
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(view, options);
}

여기서 두 가지 추가사항이 있다.
  1. legend 옵션
    • maxLines
      column 항목을 설명하는 지표가 chart의 position 옵션 위치에 나타나게 되는데, 이 항목이 많아진 경우 한 줄에 다 표시 되지 않는다.
      이 때 한 줄에 다 표시해 주고자 할 때 위 옵션을 사용할 수 있다. 단, posittion 항목이 top으로 설정된 경우에만 사용할 수 있다.
      [maxLines 옵션이 없는 경우]


      [maxLines:3 옵션이 있는 경우]

  2. hAxis 옵션
    baseline 옵션은 아래와 같이 3가지가 있으며, column 타입에 따라 기본값이 다르다.


    number format의 데이터이지만, 양수만 표현해 주기 위해서 "discrete', direction: 1 을 추가하였다.
    숫자 format 또한 설정이 가능하다.






'Programing > Web Chart' 카테고리의 다른 글

Google Chart 사용기  (0) 2015.03.05
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함