在數據分析中建立自訂 JavaScript 視覺化內容

Google 數據分析可讓使用者免費建立含有互動式資料視覺化的即時資訊主頁。使用者可以透過各種來源擷取資料,並在數據分析中製作報表,並提供完整的編輯和共用功能。以下是數據分析資訊主頁範例:

(按一下這裡在數據分析中查看範例報表)

數據分析提供了數種內建的圖表類型,包括折線圖、長條圖、圓餅圖和散佈圖。社群視覺呈現可讓您在數據分析中使用自己的自訂 JavaScript 視覺化功能。社群視覺呈現是由數據分析開發人員社群所建立,所有開發人員皆可建立社群視覺呈現。你也可以和其他人分享社群視覺呈現,讓他們將這些資料用於自己的資料。

課程內容

本程式碼研究室將說明:

  • Google 數據分析社群視覺呈現的運作方式
  • 如何使用 ds-component 輔助程式庫建構社群視覺呈現
  • 如何將社群視覺呈現整合至數據分析資訊主頁

軟硬體需求

要完成此程式碼研究室,您必須:

  • 上網和網路瀏覽器
  • Google 帳戶
  • 存取 Google Cloud Platform 儲存空間值區
  • 熟悉 JavaScript

為什麼您選擇這個程式碼研究室?

我對資料視覺化有興趣很有興趣。 我想進一步瞭解數據分析 我想打造自己的社群視覺呈現。 我想嘗試將數據分析與其他平台整合。 我對 Google Cloud 解決方案有興趣。

您打算如何使用此程式碼研究室/教學課程?

僅這次的練習 閱讀並完成練習

您對數據分析的使用體驗有什麼評價?

沒聽過 我知道這是什麼功能,但我沒用過。 我偶爾會使用。 我經常使用。 我是專家使用者。

以下哪一項敘述最符合您的背景?

開發人員 設計師/使用者體驗專家 商業/資料/財務分析師 數據資料學家/資料工程師 行銷/社交媒體/數位分析專家 其他

您對哪個 JavaScript 視覺化程式庫感興趣?

D3.js Google 排行榜 Chart.js 傳單 高圖 Plot.ly 其他

請前往下一頁提交問卷調查資訊。

透過數據分析的社群視覺呈現,您可以建立並使用可整合至資訊主頁的自訂 JavaScript 視覺化功能。

在本程式碼研究室中,您將建立長條圖圖,支援 1 種維度、1 個指標和長條顏色樣式。

如要建立社群視覺化圖表,您必須在 Google Cloud Platform 儲存空間值區中建立下列檔案,稍後即可建立該檔案。

檔案名稱

檔案類型

目的

Manifest.json*

JSON

提供視覺化資料和其他資源位置的中繼資料。

myViz.json

JSON

針對「屬性」面板提供資料和樣式設定選項。

myViz.js

JavaScript

提供顯示視覺呈現所需的 JavaScript 程式碼。

myViz.css (選填)

CSS

為視覺呈現提供樣式設定。

*資訊清單是唯一具有必要名稱的檔案。其他檔案也可以採用不同的名稱,但前提是您在資訊清單檔案中指定了檔案名稱/位置。

在本節中,您會加入處理程式碼、樣式變更和視覺化呈現所需的 JavaScript 程式碼。

寫入視覺化來源

步驟 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 });

準備最終 JavaScript 檔案

步驟 3:將視覺輔助輔助程式資料庫 (dscc.min.js) 和 myVizSource.js 檔案的內容複製到 myViz.js 檔案中,以將所有必要 JavaScript 合併成單一檔案。執行下列指令來串連檔案。在每次更新視覺呈現程式碼時重複這個步驟。

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 檔案會定義視覺呈現支援與需要的資料和樣式屬性。您將透過此程式碼研究室建構的視覺化圖表,使用單一維度和一個指標,且需要一個樣式元素才能選取顏色。進一步瞭解維度和指標

複製下列程式碼並儲存為 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 值區。建議的儲存空間級別為「地區性」。如要進一步瞭解免費方案,請造訪 Cloud Storage 定價。您的視覺化儲存空間不太可能產生 Regional Storage 類別的任何費用。

步驟 3:記下您的值區名稱/路徑,從 buckets/ 之後的部分開始。數據分析會稱之為「元件 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.jsonmyViz.jsmyViz.jsonmyViz.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:複製社群視覺呈現樣本資料集的網址。

步驟 2:前往數據分析,然後按一下「開始製作新報表」下方的 [空白]

步驟 3:按一下右下方的 [建立新資料來源]

步驟 4:選取「Google 試算表」連接器。

步驟 5:在 [網址] 欄位中,輸入您在上方步驟 1 取得的 Google 試算表網址。

步驟 6:按一下頁面右上角的 [連線]

步驟 7:在資料來源標頭中,按一下 [社群視覺呈現存取權],選取 [開啟],然後按一下 [儲存]

步驟 7:在出現的方塊中按一下 [加入報表],將資料來源加入報表。

步驟 6:按一下工具列中的社群視覺呈現按鈕 。系統隨即會開啟下拉式選單。

步驟 7:將前置字串為 gs:// ( 的值區名稱貼到「資訊清單路徑」的文字輸入欄位內,然後在「元件 ID」下方新增 barChart,然後按一下 [新增]。

您的視覺效果會自動顯示在畫布上。右側的屬性面板應顯示 myViz.json 檔案中的元素。

視覺化功能可讓您設定一個維度和一個指標。

已指定一個樣式元素 - 顯示標示為「長條顏色」的字型顏色選取器。在下一個步驟中,您將使用這個選擇器來影響視覺呈現。

在本節中,您將使用色彩選取器樣式元素來更新視覺呈現。

步驟 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:建立合併的 JavaScript 檔案,然後將視覺化檔案重新上傳到 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:建立合併的 JavaScript 檔案,然後將視覺化檔案重新上傳到 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:建立合併的 JavaScript 檔案,然後將視覺化檔案重新上傳到 Google Cloud Storage。

步驟 3:重新整理數據分析報表,在其中測試您的社群視覺呈現。您應該已經看到一個長條圖,其中有從資料中產生的標題,並使用您的 myViz.css 檔案設定樣式。

恭喜,您已在數據分析中建立社群視覺呈現!這將帶入本程式碼研究室的終點。現在,讓我們看看你可採取的後續步驟。

延長視覺呈現

利用社群視覺化功能執行更多工作

其他資源

以下幾項資源可協助您深入瞭解本程式碼研究室所涵蓋的資料。

資源類型

使用者功能

開發人員功能

說明文件

說明中心

開發人員說明文件

新聞與最新快訊

數據分析中註冊使用者設定

開發人員郵寄清單

提出問題

使用者論壇

Stack Overflow [google-data-studio]

數據分析開發人員論壇

影片

YouTube 數據分析

即將登場!

範例

報表庫

開放原始碼存放區