チュートリアル:Power BI の円形カード視覚化を開発する

このチュートリアルでは、円の中に書式設定された測定値が表示される、円形カードという名前の Power BI 視覚エフェクトを開発します。 円形カード視覚化を使用すると、塗りつぶしの色と輪郭の太さのカスタマイズがサポートされます。

このチュートリアルでは、以下の内容を学習します。

  • 視覚化の開発プロジェクトを作成します。
  • D3 視覚化要素を使用して視覚化を開発します。
  • データを処理するように視覚化を構成します。
  • サイズ変更に適合するように視覚化を構成します。
  • 視覚化に対してアダプティブな色と境界線の設定を構成します。

注意

この視覚化の完全なソース コードについては、Circle Card の Power BI 視覚エフェクトに関するページを参照してください。

前提条件

Power BI の独自の視覚化の開発を始める前に、このセクションに記載されているすべてのものがあることを確認してください。

開発プロジェクトを作成する

このセクションでは、円形カード視覚エフェクト用のプロジェクトを作成します。

注意

このチュートリアルでは、Visual Studio Code (VS Code) を使用して、Power BI の視覚化を開発します。

  1. VS Code で新しいターミナルを開き、プロジェクトを作成するフォルダーに移動します。

  2. PowerShell ターミナルに次のコマンドを入力します。

    pbiviz new CircleCard
    
  3. VS Code エクスプローラーで CircleCard フォルダーを開きます。 ([ファイル]>[フォルダーを開く])。

    Screenshot of VS code window opened to the circle card folder.

    これらの各ファイルの機能の詳細については、「Power BI 視覚化プロジェクトの構造」を参照してください。

  4. ターミナル ウィンドウを確認し、現在のディレクトリが CircleCard であることを確認します。 Power BI 視覚化ツールの依存関係をインストールします。

    npm install
    

    ヒント

    視覚化にインストールされた依存関係を確認するには、package.json ファイルを確認します。

  5. 円形カード視覚化を開始します。

    pbiviz start
    

    これで、お使いのコンピューターでホストされている間、視覚化が実行されるようになりました。

    重要

    チュートリアルを終えるまで、PowerShell ウィンドウを閉じないでください。 視覚化の実行を停止するには、Ctrl+C キーを押し、バッチ ジョブを終了するように求められたら、「Y」と入力して Enter キーを押します。

Power BI サービスで視覚エフェクトを確認する

Power BI サービスで視覚化をテストするために、US Sales Analysis レポートを使用します。 このレポートをダウンロードして、Power BI サービスにアップロードできます。

また、独自のレポートを使用して視覚化をテストすることもできます。

注意

続ける前に、視覚化開発者の設定を有効にしてあることを確認してください。

  1. PowerBI.com にサインインし、US Sales Analysis レポートを開きます。

  2. 編集 を選択します。

    Screenshot of the edit option in Power B I service.

  3. Power BI サービスのインターフェイスの下部にある [新しいページ] ボタンをクリックして、テスト用の新しいページを作成します。

    Screenshot of the new page button in Power B I service.

  4. [視覚化] ペインで、 [開発者向けビジュアル] を選択します。

    Screenshot of the developer visual in the visualizations pane.

    この視覚化は、コンピューターで実行しているカスタム視覚化を表わします。 カスタム視覚化のデバッグの設定が有効になっている場合にのみ使用できます。

  5. 視覚化がレポート キャンバスに追加されたことを確認します。

    Screenshot of the new visual added to the report.

    これは、その update メソッドが呼び出された回数を表示する簡単な視覚化です。 この段階では、視覚化にはデータは取得されていません。

    注意

    視覚化に接続エラー メッセージが表示される場合は、ブラウザーで新しいタブを開き、https://localhost:8080/assets に移動して、ブラウザーでこのアドレスを使用することを承認します。

    Screenshot of the new visual displaying a connection error.

  6. 新しい視覚化が選択されている状態で、 [フィールド] ペインに移動し、Sales を選択して、Quantity を選択します。

    Screenshot of the Power B I service quantity field in the sales table in the U S sales analysis report.

  7. 視覚化がどのように応答するかをテストするには、そのサイズを変更し、視覚化のサイズを変更するたびに Update count の値が増えることを確認します。

    Screenshot of the new visual displaying a different update count number, after being resized.

視覚化要素とテキストを追加する

このセクションでは、視覚エフェクトを円形に変換し、テキストが表示されるようにする方法について説明します。

視覚化のファイルを変更する

visual.ts ファイルを設定します。

ヒント

読みやすくするため、コード スニペットをプロジェクトにコピーするたびに、ドキュメントの書式を設定することをお勧めします。 VS Code 内の任意の場所を右クリックして、[ドキュメントのフォーマット] (または Alt+Shift+F を押す) を選択します。

  1. VS Code の [エクスプローラー] ペイン[src] フォルダーを展開して、visual.ts ファイルを選びます。

    Screenshot of accessing the visual.ts file in V S code.

  2. MIT ライセンス コメントの下にあるすべてのコードを削除します。

    重要

    visual.ts ファイルの最上部のコメントに注目してください。 Massachusetts Institute of Technology (MIT) ライセンス契約の下で、Power BI の視覚化パッケージを使用する権限が、無料で付与されます。 契約の一環として、ファイルの最上部に必ずコメントを残す必要があります。

  3. 必要なライブラリとモジュールをインポートし、d3 ライブラリの種類の選択を定義します。

    "use strict";
    
    import "./../style/visual.less";
    import powerbi from "powerbi-visuals-api";
    import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions;
    import VisualUpdateOptions = powerbi.extensibility.visual.VisualUpdateOptions;
    import IVisual = powerbi.extensibility.visual.IVisual;
    import DataView = powerbi.DataView;
    import IVisualHost = powerbi.extensibility.IVisualHost;
    import * as d3 from "d3";
    type Selection<T extends d3.BaseType> = d3.Selection<T, any, any, any>;
    

    注意

    設定時に D3 JavaScript ライブラリをインストールしなかった場合は、ここでインストールします。 PowerShell で npm i d3@latest --save を実行します

    インポートした項目に以下の項目があることに注目してください。

    • IVisualHost - 視覚化ホスト (Power BI) との対話に使用されるプロパティとサービスのコレクション。
    • "D3 ライブラリ" - データ駆動型ドキュメントを作成するための JavaScript ライブラリ。
  4. インポートの下に、空の visual クラスを作成します。 この visual クラスには、すべての視覚化が始まる IVisual インターフェイスを実装します。

    export class Visual implements IVisual {
    
    }
    

    visual クラスの内容の詳細については、「ビジュアル API」を参照してください。 このクラスは、次の 3 つの手順で定義します。

  5. visual クラスの先頭に、クラスレベルの private メソッドを追加します。

    private host: IVisualHost;
    private svg: Selection<SVGElement>;
    private container: Selection<SVGElement>;
    private circle: Selection<SVGElement>;
    private textValue: Selection<SVGElement>;
    private textLabel: Selection<SVGElement>;
    

    これらのプライベート メソッドの一部が Selection の型を使っていることに注意してください。

  6. constructor メソッドで円とテキストの要素を定義します。 このメソッドは、視覚エフェクトがインスタンス化されたときに呼び出されます。 D3 スケーラブル ベクター グラフィックス (SVG) を使うと、3 つの図形 (1 つの円と 2 つのテキスト要素) を作成できます。

    constructor(options: VisualConstructorOptions) {
        this.svg = d3.select(options.element)
            .append('svg')
            .classed('circleCard', true);
        this.container = this.svg.append("g")
            .classed('container', true);
        this.circle = this.container.append("circle")
            .classed('circle', true);
        this.textValue = this.container.append("text")
            .classed("textValue", true);
        this.textLabel = this.container.append("text")
            .classed("textLabel", true);
    }
    
  7. update メソッドを使って幅と高さを定義します。 このメソッドは、新しい値やサイズの変更など、データまたはホスト環境に変更があるたびに呼び出されます。

    public update(options: VisualUpdateOptions) {
        let width: number = options.viewport.width;
        let height: number = options.viewport.height;
        this.svg.attr("width", width);
        this.svg.attr("height", height);
        let radius: number = Math.min(width, height) / 2.2;
        this.circle
            .style("fill", "white")
            .style("fill-opacity", 0.5)
            .style("stroke", "black")
            .style("stroke-width", 2)
            .attr("r", radius)
            .attr("cx", width / 2)
            .attr("cy", height / 2);
        let fontSizeValue: number = Math.min(width, height) / 5;
        this.textValue
            .text("Value")
            .attr("x", "50%")
            .attr("y", "50%")
            .attr("dy", "0.35em")
            .attr("text-anchor", "middle")
            .style("font-size", fontSizeValue + "px");
        let fontSizeLabel: number = fontSizeValue / 4;
        this.textLabel
            .text("Label")
            .attr("x", "50%")
            .attr("y", height / 2)
            .attr("dy", fontSizeValue / 1.2)
            .attr("text-anchor", "middle")
            .style("font-size", fontSizeLabel + "px");
    }
    
  8. visual.ts ファイルを保存します。

(省略可能) 視覚化のファイル内のコードを確認する

visual.ts ファイルの最終的なコードが次のようになっていることを確認します。

/*
*  Power BI Visual CLI
*
*  Copyright (c) Microsoft Corporation
*  All rights reserved.
*  MIT License
*
*  Permission is hereby granted, free of charge, to any person obtaining a copy
*  of this software and associated documentation files (the ""Software""), to deal
*  in the Software without restriction, including without limitation the rights
*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*  copies of the Software, and to permit persons to whom the Software is
*  furnished to do so, subject to the following conditions:
*
*  The above copyright notice and this permission notice shall be included in
*  all copies or substantial portions of the Software.
*
*  THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*  THE SOFTWARE.
*/
"use strict";

import "./../style/visual.less";
import powerbi from "powerbi-visuals-api";
import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions;
import VisualUpdateOptions = powerbi.extensibility.visual.VisualUpdateOptions;
import IVisual = powerbi.extensibility.visual.IVisual;
import DataView = powerbi.DataView;
import IVisualHost = powerbi.extensibility.IVisualHost;
import * as d3 from "d3";
type Selection<T extends d3.BaseType> = d3.Selection<T, any, any, any>;

export class Visual implements IVisual {
    private host: IVisualHost;
    private svg: Selection<SVGElement>;
    private container: Selection<SVGElement>;
    private circle: Selection<SVGElement>;
    private textValue: Selection<SVGElement>;
    private textLabel: Selection<SVGElement>;
    
    constructor(options: VisualConstructorOptions) {
        this.svg = d3.select(options.element)
            .append('svg')
            .classed('circleCard', true);
        this.container = this.svg.append("g")
            .classed('container', true);
        this.circle = this.container.append("circle")
            .classed('circle', true);
        this.textValue = this.container.append("text")
            .classed("textValue", true);
        this.textLabel = this.container.append("text")
            .classed("textLabel", true);
    }
    
    public update(options: VisualUpdateOptions) {
        let width: number = options.viewport.width;
        let height: number = options.viewport.height;
        this.svg.attr("width", width);
        this.svg.attr("height", height);
        let radius: number = Math.min(width, height) / 2.2;
        this.circle
            .style("fill", "white")
            .style("fill-opacity", 0.5)
            .style("stroke", "black")
            .style("stroke-width", 2)
            .attr("r", radius)
            .attr("cx", width / 2)
            .attr("cy", height / 2);
        let fontSizeValue: number = Math.min(width, height) / 5;
        this.textValue
            .text("Value")
            .attr("x", "50%")
            .attr("y", "50%")
            .attr("dy", "0.35em")
            .attr("text-anchor", "middle")
            .style("font-size", fontSizeValue + "px");
        let fontSizeLabel: number = fontSizeValue / 4;
        this.textLabel
            .text("Label")
            .attr("x", "50%")
            .attr("y", height / 2)
            .attr("dy", fontSizeValue / 1.2)
            .attr("text-anchor", "middle")
            .style("font-size", fontSizeLabel + "px");
    }
}

capabilities ファイルを変更する

円カード視覚エフェクトは単純な視覚エフェクトです。[書式] ペインにオブジェクトは作成されません。 そのため、このファイルの objects セクションを削除しても問題ありません。

  1. VS Code でプロジェクトを開きます ( [ファイル]>[フォルダーを開く] )。

  2. capabilities.json ファイルを選択します。

    Screenshot of accessing the capabilities.json file in V S code.

  3. objects 配列全体を削除します。
    dataRolesdataViewMappings の間に空行を残さないでください。

  4. capabilities.json ファイルを保存します。

円形カード視覚化を再起動する

視覚化の実行を停止して再起動します。

  1. 視覚化を開始した [PowerShell] ウィンドウで Ctrl+C キーを押します。 バッチ ジョブの終了を求められたら、「Y」と入力して Enter キーを押します。

  2. PowerShell で、もう一度視覚化を開始します。

    pbiviz start
    

追加した要素を使用して視覚化をテストする

視覚化に新しく追加した要素が表示されることを確認します。

  1. Power BI サービスで、Power BI US Sales Analysis レポートを開きます。 別のレポートを使用して円形カード視覚化を開発している場合は、そのレポートに移動します。

  2. [メジャー] ボックスに値をドラッグし、視覚エフェクトの形状が円になることを確認します。

    Screenshot of the circle card visual shaped as a circle.

    視覚化に何も表示されない場合は、 [フィールド] ペインから Quantity フィールドを開発者向け視覚化にドラッグします。

  3. ビジュアルのサイズを変更します。

    視覚化の寸法に合わせて円とテキストが拡大縮小されることを確認します。 視覚化のサイズを変更すると update メソッドが呼び出され、その結果、視覚化の要素が再び拡大縮小されます。

自動再読み込みを有効にする

プロジェクトの変更を保存するたびに、視覚化が自動的に再度読み込まれるようにするには、この設定を使用します。

  1. Power BI US Sales Analysis レポート (または、円形カード視覚化が含まれるプロジェクト) に移動します。

  2. 円形カード視覚化を選択します。

  3. フローティング ツール バーで、 [自動再読み込みの切り替え] を選択します。

    Screenshot of clicking the toggle auto reload option, in the circle card visual floating toolbar.

視覚化でデータを処理する

このセクションでは、データ ロールとデータ ビュー マッピングを定義します。 また、表示されている値の名前を表示するように視覚エフェクトを変更します。

capabilities ファイルを構成する

capabilities.json ファイルを変更して、データ ロール、オブジェクト、データ ビューのマッピングを定義します。

  • データ ロールの定義

    measure 型の単一のデータ ロールで dataRoles 配列を定義します。 このデータ ロールは measure と呼ばれ、Measure と表示されます。 それを使用して、メジャー フィールドまたは集計されたフィールドのどちらかを渡すことができます。

    1. VS Code で capabilities.json ファイルを開きます。

    2. dataRoles 配列内のすべての内容を削除します。

    3. dataRoles 配列に次のコードを挿入します。

      {
          "displayName": "Measure",
          "name": "measure",
          "kind": "Measure"
      }
      
    4. capabilities.json ファイルを保存します。

  • データ ビュー マッピングの定義

    dataViewMappings 配列に measure という名前のフィールドを定義します。 このフィールドは、データ ロールに渡すことができます。

    1. VS Code で capabilities.json ファイルを開きます。

    2. dataViewMappings 配列内のすべての内容を削除します。

    3. dataViewMappings 配列に次のコードを挿入します。

      {
          "conditions": [
              { "measure": { "max": 1 } }
          ],
          "single": {
              "role": "measure"
          }
      }
      
    4. capabilities.json ファイルを保存します。

capabilities.json ファイルが次のようになることを確認します。

{
    "dataRoles": [
        {
            "displayName": "Measure",
            "name": "measure",
            "kind": "Measure"
        }
    ],
    "dataViewMappings": [
        {
            "conditions": [
                { "measure": { "max": 1 } }
            ],
            "single": {
                "role": "measure"
            }
        }
    ],
    "privileges": []
}

(省略可能) capabilities ファイルのコードの変更を確認する

円形カード視覚化に measure フィールドが表示されることを確認し、 [Dataview の表示] オプションを使用して行った変更を確認します。

  1. Power BI サービスで、Power BI US Sales Analysis レポートを開きます。 別のレポートを使用して円形カード視覚化を開発している場合は、そのレポートに移動します。

  2. 円形カード視覚化を Measure というタイトルのフィールドで構成できることに注意してください。 [フィールド] ペインから Measure フィールドに要素をドラッグ アンド ドロップできます。

    Screenshot of the circle card measure filed, in the Power BI service visualization pane.

    Note

    ビジュアル プロジェクトには、データ バインド ロジックがまだ含まれていません。

  3. フローティング ツール バーで、 [Dataview の表示] を選択します。

    Screenshot of the show dataview button, located in the circle card floating toolbar.

  4. 3 つの点を選択して表示を展開し、single を選択して value を表示します。

    Screenshot of the value figure as it's displayed in the circle card show dataview option.

  5. metadata を展開し、columns 配列を展開して、formatdisplayName の値を確認します。

    Screenshot of the format and display name values as displayed in the circle card show dataview option.

  6. もう一度ビジュアルに切り替えて、ビジュアルの上に表示されるツールバーで、[Dataview の表示] を選択します。

データを使用するように視覚化を構成する

これまでのところ、視覚エフェクトはレンダリングされますが、データは表示されません。 このセクションでは、visual.ts ファイルを変更し、円形カード視覚エフェクトでデータを使用できるようにします。

  1. VS Code で visual.ts ファイルを開きます。

  2. update メソッドで次の手順を実行します。

    • 最初のステートメントとして次のステートメントを追加します。 このステートメントにより、簡単にアクセスできるように dataView が変数に割り当てられ、dataView オブジェクトを参照するように変数が宣言されます。

      let dataView: DataView = options.dataViews[0];
      
    • .text("Value") を次のコード行に置き換えます。

      .text(<string>dataView.single.value)
      
    • .text("Label") を次のコード行に置き換えます。

      .text(dataView.metadata.columns[0].displayName)
      
  3. visual.ts ファイルを保存します。

  4. Power BI サービスで視覚エフェクトを確認します。

視覚化に、選択したデータ フィールドの名前と値が表示されるようになりました。

Screenshot of a circle card visual displaying the quantity value.

これで、作業中の Power BI 視覚化が作成されました。 これに対して、書式設定オプションの追加、またはすぐに使用できるようにパッケージ化を行うことができます。

次のステップ