데이터 스튜디오에서 맞춤 자바스크립트 시각화 만들기

Google 데이터 스튜디오를 사용하면 멋진 데이터 시각화를 통해 실시간 양방향 대시보드를 무료로 구축할 수 있습니다. 사용자는 완전한 수정 및 공유 기능을 사용하여 다양한 소스에서 데이터를 가져오고 데이터 스튜디오에서 보고서를 만들 수 있습니다. 다음은 데이터 스튜디오 대시보드의 예입니다.

(데이터 스튜디오에서 예시 보고서 보기)

데이터 스튜디오에서는 선 차트, 막대 그래프, 원형 차트, 산점도 등 기본적인 여러 차트 유형을 제공합니다. 커뮤니티 시각화를 사용하면 데이터 스튜디오에서 나만의 맞춤 자바스크립트 시각화를 만들고 사용할 수 있습니다. 커뮤니티 시각화는 데이터 스튜디오 개발자 커뮤니티에서 빌드하며, 모든 개발자가 이 시각화를 빌드할 수 있습니다. 커뮤니티 시각화를 다른 사용자가 자신의 데이터와 함께 사용할 수 있도록 공유할 수도 있습니다.

학습할 내용

이 Codelab에서는 다음에 관해 알아봅니다.

  • Google 데이터 스튜디오 커뮤니티 시각화 작동 방식
  • ds-구성요소 도우미 라이브러리를 사용하여 커뮤니티 시각화를 빌드하는 방법
  • 커뮤니티 시각화를 데이터 스튜디오 대시보드에 통합하는 방법

필요한 항목

이 Codelab을 완료하려면 다음이 필요합니다.

  • 인터넷 및 웹브라우저에 대한 액세스
  • Google 계정
  • Google Cloud Platform 스토리지 버킷에 대한 액세스
  • 자바스크립트에 대한 기본 지식

이 Codelab을 선택한 이유는 무엇인가요?

일반적인 데이터 시각화에 관심이 있습니다. 데이터 스튜디오에 관해 자세히 알아보고 싶습니다. 나만의 커뮤니티 시각화를 만들고 싶습니다. 데이터 스튜디오를 다른 플랫폼과 통합하려고 합니다. Google Cloud 솔루션에 관심이 있습니다.

이 Codelab/튜토리얼을 어떻게 사용할 계획인가요?

요약만 보기 읽은 후 실습 활동을 완료하세요.

데이터 스튜디오 사용 경험이 어떠셨나요?

들어본 적 없음 이게 무엇인지는 알고 있지만 사용하지는 않습니다. 가끔 사용합니다. 저는 정기적으로 사용합니다 전문가입니다.

배경을 가장 잘 설명하는 것은 무엇인가요?

개발자 디자이너/UX 전문가 비즈니스/데이터/재무 분석가 데이터 과학자/데이터 엔지니어 마케팅/소셜 미디어/디지털 애널리틱스 전문가 기타

어떤 자바스크립트 시각화 라이브러리에 관심이 있으신가요?

D3.js Google 차트 Chart.js Leaflet Highcharts Plot.ly 기타

다음 페이지로 이동하여 설문조사 정보를 제출합니다.

데이터 스튜디오 커뮤니티 시각화를 사용하면 맞춤 자바스크립트 시각화를 만들고 이를 대시보드에 통합할 수 있습니다.

이 Codelab에서는 측정기준 1개, 측정항목 1개, 막대 색상 스타일을 지원하는 막대 그래프 커뮤니티 시각화를 만듭니다.

커뮤니티 시각화를 만들려면 Google Cloud Platform 스토리지 버킷에 다음 파일이 필요합니다. 이 파일은 이후 단계에서 만듭니다.

파일 이름

파일 형식

목적

manifest.json*

JSON

시각화 및 다른 리소스의 위치에 대한 메타데이터를 제공합니다.

myViz.json

JSON

속성 패널에 데이터 및 스타일 구성 옵션을 제공합니다.

myViz.js

자바스크립트

시각화를 표시하는 데 필요한 자바스크립트 코드를 제공합니다.

myViz.css (선택사항)

CSS

시각화의 스타일을 지정합니다.

*매니페스트가 필요한 이름을 가진 유일한 파일입니다. 다른 파일의 이름은 매니페스트 파일에 지정된 이름/위치만 지정하면 됩니다.

이 섹션에서는 데이터, 스타일 변경, 시각화 렌더링을 처리하는 데 필요한 코드를 자바스크립트 파일에 추가합니다.

시각화 소스 작성

1단계: 데이터 스튜디오 커뮤니티 구성요소 라이브러리에서 dscc.min.js 파일을 다운로드하여 작업 디렉터리에 복사합니다.

2단계: 다음 코드를 텍스트 편집기에 복사하여 로컬 작업 디렉터리에 myVizSource.js로 저장합니다.

myVizSource.js

function drawViz(data) {

  // set margins + canvas size
  const margin = { top: 10, bottom: 50, right: 10, left: 10 };
  const height = dscc.getHeight() - margin.top - margin.bottom;
  const width = dscc.getWidth() - margin.left - margin.right;

  // remove the svg if it already exists
  if (document.querySelector("svg")) {
    let oldSvg = document.querySelector("svg");
    oldSvg.parentNode.removeChild(oldSvg);
  }

  const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg.setAttribute("height", `${height}px`);
  svg.setAttribute("width", `${width}px`);

  const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
  rect.setAttribute('width', `${width/2}px`);
  rect.setAttribute('height', `${height/2}px`);
  rect.style.fill =  'blue';

  svg.append(rect);

  document.body.appendChild(svg);
}
// subscribe to data and style changes
dscc.subscribeToData(drawViz, { transform: dscc.objectTransform });

최종 자바스크립트 파일 준비

3단계: 시각화 도우미 라이브러리(dscc.min.js)와 myVizSource.js 파일의 콘텐츠를 myViz.js이라는 새 파일에 복사하여 필요한 모든 자바스크립트를 단일 파일로 결합합니다. 다음 명령어를 실행하여 파일을 연결합니다. 시각화 코드를 업데이트할 때마다 이 단계를 반복합니다.

Linux/Mac OS 연결 스크립트

cat dscc.min.js > myViz.js
echo >> myViz.js
cat myVizSource.js >> myViz.js

Windows 스크립트

del myViz.js
type nul > myViz.js
type dscc.min.js >> myViz.js
echo.>> myViz.js
type myVizSource.js >> myViz.js

CSS 파일에서 시각화의 스타일을 정의합니다. 다음 코드를 복사하여 myViz.css.로 저장합니다.

myViz.css

#myVizTitle {
  color: black;
  font-size: 24px;
  text-align: center;
  margin: 0 auto;
}

시각화 구성 json 파일은 시각화에서 지원 및하는 데이터와 스타일 속성을 정의합니다. 이 Codelab에서 빌드할 이 시각화는 하나의 측정기준과 하나의 측정항목을 지원하며 색상을 선택하려면 하나의 스타일 요소가 필요합니다. 측정기준 및 측정항목에 대해 자세히 알아보기

다음 코드를 복사하여 myViz.json.로 저장합니다. 구성할 수 있는 속성에 관해 자세히 알아보려면 구성 참조 문서를 참고하세요.

myViz.json

{
  "data": [
    {
      "id": "concepts",
      "label": "Concepts",
      "elements": [
        {
          "id": "barDimension",
          "label": "Dimension",
          "type": "DIMENSION",
          "options": {
            "min": 1,
            "max": 1
          }
        },
        {
          "id": "barMetric",
          "label": "Metric",
          "type": "METRIC",
          "options": {
            "min": 1,
            "max": 1
          }
        }
      ]
    }
  ],
  "style": [
    {
      "id": "color",
      "label": "Colors",
      "elements": [
        {
          "type": "FONT_COLOR",
          "id": "barColor",
          "label": "Bar Color",
          "defaultValue": "black"
        }
      ]
    }
  ]
}

1단계: Google Cloud Platform (GCP) 프로젝트 만들기

2단계: GCP 버킷 만들기 권장되는 스토리지 클래스는 Regional입니다. 무료 등급에 대한 자세한 내용은 Cloud Storage 가격 책정을 참조하세요. Regional Storage 클래스에 대한 시각화 스토리지로 인해 비용이 발생할 가능성은 거의 없습니다.

3단계: 버킷/ 이후의 섹션부터 시작되는 버킷 이름/경로를 기록해 둡니다. 데이터 스튜디오는 이를 '구성요소 ID'라고 하며 이 ID를 식별하고 배포하는 데 사용됩니다.

매니페스트 파일은 시각화 위치와 리소스에 대한 정보를 제공합니다. 이름을 "manifest.json"로 지정해야 하며 이전 단계에서 만든 버킷 (구성요소 ID에 사용한 것과 동일해야 함)에 있어야 합니다.

다음 코드를 텍스트 편집기에 복사하여 manifest.json.로 저장합니다.

매니페스트를 자세히 알아보려면 매니페스트 참조 문서를 확인하세요.

manifest.json

{
  "name": "Community Visualization",
  "logoUrl": "https://raw.githubusercontent.com/googledatastudio/community-visualizations/master/docs/codelab/img/bar_chart.png",
  "organization": "Data Studio Codelab",
  "supportUrl": "https://url",
  "packageUrl": "https://url",
  "privacyPolicyUrl": "https://url",
  "description": "Community Visualization Codelab",
  "devMode": true,
  "components": [{
    "id": "barChart",
    "name": "Bar Chart",
    "iconUrl": "https://raw.githubusercontent.com/googledatastudio/community-visualizations/master/docs/codelab/img/bar_chart.png",
    "description": "Bar chart written in d3.js",
    "resource": {
      "js": "MY_GOOGLE_CLOUD_STORAGE_BUCKET/myViz.js",
      "config": "MY_GOOGLE_CLOUD_STORAGE_BUCKET/myViz.json",
      "css": "MY_GOOGLE_CLOUD_STORAGE_BUCKET/myViz.css"
    }
  }]
}
  1. 웹 인터페이스 또는 gsutil 명령줄 도구를 사용하여 manifest.json, myViz.js, myViz.json, myViz.css 파일을 Google Cloud Storage 버킷에 업로드합니다. 시각화를 업데이트할 때마다 이 작업을 반복합니다.

gsutil 업로드 명령어

gsutil cp -a public-read manifest.json gs://MY_GOOGLE_CLOUD_STORAGE_BUCKET
gsutil cp -a public-read myViz.* gs://MY_GOOGLE_CLOUD_STORAGE_BUCKET

1단계: 커뮤니티 시각화 샘플 데이터 세트의 URL을 복사합니다.

2단계: 데이터 스튜디오로 이동하여 새 보고서 시작에서 빈 양식을 클릭합니다.

3단계: 오른쪽 하단에서 새 데이터 소스 만들기를 클릭합니다.

4단계: Google Sheets 커넥터를 선택합니다.

5단계: URL 입력란에 위 1단계에서 Google 시트의 URL을 입력합니다.

6단계: 페이지 오른쪽 상단에서 연결을 클릭합니다.

7단계: 데이터 소스 헤더에서 커뮤니티 시각화 액세스를 클릭하고 사용을 선택한 후 저장을 클릭합니다.

7단계: 상자에서 데이터 추가를 클릭하여 데이터 소스를 보고서에 추가합니다.

6단계: 툴바에서 커뮤니티 시각화 버튼 을 클릭합니다. 드롭다운이 열립니다.

7단계: gs:// (로 시작하는 버킷 이름(예: gs://community-viz-docs/myViz))을 "Manifest Path"의 텍스트 입력에 붙여넣고 "Component ID," 아래에 barChart을 추가한 후 "ADD"를 클릭합니다.

시각화가 캔버스에 자동으로 그려집니다. 오른쪽의 속성 패널에는 myViz.json 파일의 요소가 반영되어야 합니다.

시각화에서는 측정기준 1개와 측정항목 1개를 사용할 수 있습니다.

스타일 요소 1개가 지정되었습니다. 글꼴 색상 선택기는 '막대 색상'.\'t;으로 지정됩니다. 다음 단계에서는 이 선택기를 사용하여 시각화에 영향을 미칩니다.

이 섹션에서는 색상 선택기 스타일 요소를 사용하여 시각화를 업데이트합니다.

1단계: myVizSource.js 파일의 코드를 아래 코드로 바꿉니다.

myVizSource.js

function drawViz(data) {

  // set margins + canvas size
  const margin = { top: 10, bottom: 50, right: 10, left: 10 };
  const height = dscc.getHeight() - margin.top - margin.bottom;
  const width = dscc.getWidth() - margin.left - margin.right;

  // remove the svg if it already exists
  if (document.querySelector("svg")) {
    let oldSvg = document.querySelector("svg");
    oldSvg.parentNode.removeChild(oldSvg);
  }

  const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg.setAttribute("height", `${height}px`);
  svg.setAttribute("width", `${width}px`);

  const fillColor =  data.style.barColor.value
  ? data.style.barColor.value.color
  : data.style.barColor.defaultValue;

  const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
  rect.setAttribute('width', `${width/2}px`);
  rect.setAttribute('height', `${height/2}px`);
  rect.style.fill =  fillColor;
  svg.append(rect);

  document.body.appendChild(svg);
}
// subscribe to data and style changes
dscc.subscribeToData(drawViz, { transform: dscc.objectTransform });

2단계: 결합된 자바스크립트 파일을 만든 후 시각화 파일을 Google Cloud Storage에 다시 업로드합니다.

3단계: 커뮤니티 시각화를 테스트한 데이터 스튜디오 보고서를 새로고침합니다.

스타일 메뉴의 선택기를 사용하여 직사각형의 색상을 변경할 수 있어야 합니다.

이 섹션에서는 커뮤니티 시각화 샘플 데이터 세트의 데이터를 사용하여 막대 그래프를 그리도록 시각화를 업데이트합니다. 참고: 데이터 스튜디오는 시각화에 최대 2,500행의 데이터를 반환합니다.

1단계: myVizSource.js 파일의 코드를 아래 코드로 바꿉니다.

myVizSource.js

function drawViz(data) {
  let rowData = data.tables.DEFAULT;

  // set margins + canvas size
  const margin = { top: 10, bottom: 50, right: 10, left: 10 };
  const padding = { top: 15, bottom: 15 };
  const height = dscc.getHeight() - margin.top - margin.bottom;
  const width = dscc.getWidth() - margin.left - margin.right;

  // remove the svg if it already exists
  if (document.querySelector("svg")) {
    let oldSvg = document.querySelector("svg");
    oldSvg.parentNode.removeChild(oldSvg);
  }

  const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg.setAttribute("height", `${height}px`);
  svg.setAttribute("width", `${width}px`);

  const fillColor =  data.style.barColor.value
  ? data.style.barColor.value.color
  : data.style.barColor.defaultValue;

  const maxBarHeight = height - padding.top - padding.bottom;
  const barWidth = width / (rowData.length * 2);

  // obtain the maximum bar metric value for scaling purposes
  let largestMetric = 0;

  rowData.forEach(function(row) {
    largestMetric = Math.max(largestMetric, row["barMetric"][0]);
  });

  rowData.forEach(function(row, i) {
    // 'barDimension' and 'barMetric' come from the id defined in myViz.json
    // 'dimId' is Data Studio's unique field ID, used for the filter interaction
    const barData = {
      dim: row["barDimension"][0],
      met: row["barMetric"][0],
      dimId: data.fields["barDimension"][0].id
    };

    // calculates the height of the bar using the row value, maximum bar
    // height, and the maximum metric value calculated earlier
    let barHeight = Math.round((barData["met"] * maxBarHeight) / largestMetric);

    // normalizes the x coordinate of the bar based on the width of the convas
    // and the width of the bar
    let barX = (width / rowData.length) * i + barWidth / 2;

    // create the "bar"
    let rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    rect.setAttribute("x", barX);
    rect.setAttribute("y", maxBarHeight - barHeight);
    rect.setAttribute("width", barWidth);
    rect.setAttribute("height", barHeight);
    rect.setAttribute("data", JSON.stringify(barData));
    rect.style.fill = fillColor;
    svg.appendChild(rect);

    // add text labels
    let text = document.createElementNS("http://www.w3.org/2000/svg", "text");
    let textX = barX + barWidth / 2;
    text.setAttribute("x", textX);
    text.setAttribute("text-anchor", "middle");
    let textY = maxBarHeight + padding.top;
    text.setAttribute("y", textY);
    text.setAttribute("fill", fillColor)
    text.innerHTML = barData["dim"];

    svg.appendChild(text);
  });

  document.body.appendChild(svg);
}

// subscribe to data and style changes
dscc.subscribeToData(drawViz, { transform: dscc.objectTransform });

2단계: 결합된 자바스크립트 파일을 만든 후 시각화 파일을 Google Cloud Storage에 다시 업로드합니다.

3단계: 커뮤니티 시각화를 테스트한 데이터 스튜디오 보고서를 새로고침합니다. Google 시트의 데이터에서 생성된 라벨이 있는 막대 그래프가 있어야 합니다. 막대의 색상을 변경하려면 스타일 "바 색상" 선택기에서 선택한 색상을 변경합니다.

이 섹션에서는 커뮤니티 시각화 샘플 데이터 세트의 데이터를 사용하여 막대 그래프를 그리도록 시각화를 업데이트합니다.

1단계: myVizSource.js 파일의 코드를 아래 코드로 바꿉니다.

myVizSource.js

// create a title element
var titleElement = document.createElement('div');
titleElement.id = 'myVizTitle';
document.body.appendChild(titleElement);

function drawViz(data) {
  let rowData = data.tables.DEFAULT;

  // set margins + canvas size
  const margin = { top: 10, bottom: 50, right: 10, left: 10 };
  const padding = { top: 15, bottom: 15 };
  const height = dscc.getHeight() - margin.top - margin.bottom;
  const width = dscc.getWidth() - margin.left - margin.right;

  const fillColor =  data.style.barColor.value
  ? data.style.barColor.value.color
  : data.style.barColor.defaultValue;

  // remove the svg if it already exists
  if (document.querySelector("svg")) {
    let oldSvg = document.querySelector("svg");
    oldSvg.parentNode.removeChild(oldSvg);
  }

  const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg.setAttribute("height", `${height}px`);
  svg.setAttribute("width", `${width}px`);

  const maxBarHeight = height - padding.top - padding.bottom;
  const barWidth = width / (rowData.length * 2);

  // obtain the maximum bar metric value for scaling purposes
  let largestMetric = 0;

  rowData.forEach(function (row) {
    largestMetric = Math.max(largestMetric, row["barMetric"][0]);
  });

  rowData.forEach(function (row, i) {
    // 'barDimension' and 'barMetric' come from the id defined in myViz.json
    // 'dimId' is Data Studio's unique field ID, used for the filter interaction
    const barData = {
      dim: row["barDimension"][0],
      met: row["barMetric"][0],
      dimId: data.fields["barDimension"][0].id
    };

    // calculates the height of the bar using the row value, maximum bar
    // height, and the maximum metric value calculated earlier
    let barHeight = Math.round((barData["met"] * maxBarHeight) / largestMetric);

    // normalizes the x coordinate of the bar based on the width of the convas
    // and the width of the bar
    let barX = (width / rowData.length) * i + barWidth / 2;

    // create the "bar"
    let rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    rect.setAttribute("x", barX);
    rect.setAttribute("y", maxBarHeight - barHeight);
    rect.setAttribute("width", barWidth);
    rect.setAttribute("height", barHeight);
    rect.setAttribute("data", JSON.stringify(barData));
    // use style selector from Data Studio
    rect.style.fill = fillColor;
    svg.appendChild(rect);

    // add text labels
    let text = document.createElementNS("http://www.w3.org/2000/svg", "text");
    let textX = barX + barWidth / 2;
    text.setAttribute("x", textX);
    text.setAttribute("text-anchor", "middle");
    let textY = maxBarHeight + padding.top;
    text.setAttribute("y", textY);
    text.setAttribute("fill", fillColor)
    text.innerHTML = barData["dim"];

    svg.appendChild(text);
  });

  document.body.appendChild(svg);

  // Get the human-readable name of the metric and dimension

  var metricName = data.fields['barMetric'][0].name;
  var dimensionName = data.fields['barDimension'][0].name;

  titleElement.innerText = metricName + ' by ' + dimensionName;

}

dscc.subscribeToData(drawViz, { transform: dscc.objectTransform });

2단계: 결합된 자바스크립트 파일을 만든 후 시각화 파일을 Google Cloud Storage에 다시 업로드합니다.

3단계: 커뮤니티 시각화를 테스트한 데이터 스튜디오 보고서를 새로고침합니다. 데이터에서 생성되고 myViz.css 파일을 사용하여 스타일이 지정된 막대 그래프가 있어야 합니다.

축하합니다. 데이터 스튜디오에서 커뮤니티 시각화를 만들었습니다. 이제 이 Codelab을 마칩니다. 이제 어떤 조치를 취할 수 있는지 확인해 보겠습니다.

시각화 확장

커뮤니티 시각화를 더 많이 활용하세요

추가 리소스

다음은 이 Codelab에서 다루는 자료를 자세히 살펴보는 데 도움이 되는 다양한 리소스입니다.

리소스 유형

사용자 기능

개발자 기능

문서

고객센터

개발자 문서

뉴스 및 업데이트

데이터 스튜디오에 로그인 & 사용자 설정

개발자 메일링 리스트

질문하기

사용자 포럼

Stack Overflow[google-data-studio]

데이터 스튜디오 개발자 포럼

동영상

YouTube 데이터 스튜디오

곧 찾아옵니다

보고서 갤러리

오픈소스 저장소