자습서: Power BI 원 카드 시각적 개체 개발

이 자습서에서는 원 안에 서식이 지정된 측정값을 표시하는 원 카드라는 Power BI 시각적 개체를 개발합니다. 원 카드 시각적 개체는 채우기 색 및 윤곽선 두께를 사용자 지정할 수 있습니다.

이 자습서에서는 다음을 하는 방법을 알아볼 수 있습니다.

  • 시각적 개체에 대한 개발 프로젝트 만들기
  • D3 시각적 개체 요소를 사용하여 시각적 개체 개발
  • 데이터를 처리하도록 시각적 개체 구성
  • 크기 변경에 맞게 시각적 개체를 구성합니다.
  • 시각적 개체에 대한 적응형 색과 테두리 설정을 구성합니다.

참고 항목

이 시각적 개체의 전체 소스 코드는 원 카드 Power BI 시각적 개체를 참조하세요.

필수 조건

Power BI 시각적 개체 개발을 시작하기 전에, 이 섹션에 나열된 모든 것이 준비되어 있는지 확인합니다.

개발 프로젝트 만들기

이 섹션에서는 원 카드 시각적 개체에 대한 프로젝트를 만듭니다.

참고 항목

이 자습서에서는 VS Code(Visual Studio 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
    

    시각적 개체는 컴퓨터에서 호스트되는 동안 실행됩니다.

    Important

    자습서를 마칠 때까지 PowerShell 창을 닫지 마세요. 시각적 개체의 실행을 중지하려면 Ctrl+C를 입력하고, 일괄 처리 작업을 종료하라는 메시지가 표시되면 Y를 입력하고 Enter 키를 누릅니다.

Power BI 서비스에서 시각적 개체 보기

Power BI 서비스에서 시각적 개체를 테스트하기 위해 미국 영업 분석 보고서를 사용하겠습니다. 이 보고서를 다운로드하여 Power BI 서비스에 업로드할 수 있습니다.

자체 보고서를 사용하여 시각적 개체를 테스트할 수도 있습니다.

참고 항목

계속하기 전에, 시각적 개체 개발자 설정을 활성화했는지 확인합니다.

  1. PowerBI.com에 로그인하여 미국 영업 분석 보고서를 엽니다.

  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. 새로운 시각적 개체를 선택한 상태에서 필드 창으로 이동하고, 영업을 확장하고, 수량을 선택합니다.

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

  7. 시각적 개체가 어떻게 응답하는지 테스트하려면 시각적 개체의 크기를 조정합니다. 시각적 개체의 크기를 조정할 때마다 업데이트 횟수 값이 증가합니다.

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

시각적 요소 및 텍스트 추가

이 섹션에서는 시각적 개체를 원으로 바꾸고 텍스트를 표시하는 방법을 배웁니다.

시각적 개체 파일 수정

visual.ts 파일을 설정합니다.

가독성을 개선하기 위해, 코드 조각을 프로젝트에 복사할 때마다 문서의 서식을 지정하는 것이 좋습니다. VS Code에서 아무 곳이나 마우스 오른쪽 단추로 클릭하고 문서 서식 지정(또는 Alt+Shift+F 입력)을 선택합니다.

  1. VS 코드에서 탐색기 창src 폴더를 확장한 다음, visual.ts 파일을 선택합니다.

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

  2. MIT 라이선스 주석 아래의 모든 코드를 제거합니다.

    Important

    visual.ts 파일의 맨 위에 있는 설명을 확인합니다. Power BI 시각적 개체 패키지를 사용할 권한은 MIT(매사추세츠공과대학교) 라이선스의 약관에 따라 무료로 부여됩니다. 계약의 일부로 파일 맨 위에 설명을 남겨 두어야 합니다.

  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. 가져오기 아래에 빈 시각적 개체 클래스를 만듭니다. 시각적 개체 클래스는 모든 시각적 개체가 시작되는 IVisual 인터페이스를 구현합니다.

    export class Visual implements IVisual {
    
    }
    

    시각적 클래스에 들어가는 항목에 대한 자세한 내용은 Visual API를 참조하세요. 다음 세 단계에서는 이 클래스를 정의합니다.

  5. 시각적 개체 클래스의 시작 부분에 클래스 수준 private 메서드를 추가합니다.

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

    이러한 프라이빗 메서드 중 일부는 선택 유형을 사용합니다.

  6. 생성자 메서드에서 원 및 텍스트 요소를 정의합니다. 이 메서드는 시각적 개체가 인스턴스화될 때 호출됩니다. D3 SVG(확장 가능한 벡터 그래픽)를 사용하면 원과 두 개의 텍스트 요소의 세 가지 셰이프를 만들 수 있습니다.

    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");
    }
}

기능 파일 수정

원 카드 시각적 개체는 서식 창에서 개체를 만들지 않는 간단한 시각적 개체입니다. 따라서 파일의 개체 섹션을 안전하게 제거할 수 있습니다.

  1. VS Code에서 프로젝트를 엽니다(파일>폴더 열기).

  2. capabilities.json 파일을 선택합니다.

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

  3. 전체 개체 배열을 제거합니다.
    dataRolesdataViewMappings 사이에 빈 줄을 두지 마세요.

  4. capabilities.json 파일을 저장합니다.

원 카드 시각적 개체를 다시 시작합니다.

시각적 개체의 실행을 중지했다가 다시 시작합니다.

  1. 시각적 개체를 시작한 PowerShell 창에서 Ctrl+C를 입력합니다. 일괄 작업을 종료하라는 메시지가 표시되면 Y를 입력한 다음 Enter를 입력합니다.

  2. 다시 PowerShell에서 시각적 개체를 시작합니다.

    pbiviz start
    

추가된 요소를 사용하여 시각적 개체 테스트

시각적 개체가 새로 추가된 요소를 표시하는지 확인합니다.

  1. Power BI 서비스에서 Power BI 미국 영업 분석 보고서를 엽니다. 다른 보고서를 사용하여 원 카드 시각적 개체를 개발하는 경우 해당 보고서로 이동합니다.

  2. 값을 측정값 상자로 끌어서 시각적 개체가 원 모양인지 확인합니다.

    Screenshot of the circle card visual shaped as a circle.

    시각적 개체가 아무 것도 표시하지 않는 경우 필드 창에서 수량 필드를 개발자 시각적 개체로 끌어옵니다.

  3. 시각적 개체 크기를 조정합니다.

    원 및 텍스트가 시각적 개체의 크기에 맞게 스케일링됩니다. update 메서드는 시각적 개체의 크기를 조정할 때 호출되며, 호출의 결과로 시각적 요소가 다시 스케일링됩니다.

자동 다시 로드 사용

프로젝트 변경 내용을 저장할 때마다 시각적 개체가 자동으로 다시 로드되도록 이 설정을 사용하세요.

  1. Power BI 미국 영업 분석 보고서(또는 원 카드 시각적 개체가 들어 있는 프로젝트)로 이동합니다.

  2. 원 카드 시각적 개체를 선택합니다.

  3. 부동 도구 모음에서 자동 다시 로드 설정/해제를 선택합니다.

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

데이터를 처리하는 시각적 개체 가져오기

이 섹션에서는 데이터 역할 및 데이터 보기 매핑을 정의합니다. 또한 시각적 개체에서 표시하는 값의 이름을 표시하도록 시각적 개체를 수정합니다.

기능 파일 구성

capabilities.json 파일을 수정하여 데이터 역할, 개체, 데이터 보기 매핑을 정의합니다.

  • 데이터 역할 정의

    측정값 형식의 단일 데이터 역할을 사용하여 dataRoles 배열을 정의합니다. 이 데이터 역할을 측정값이라고 하며 측정값으로 표시됩니다. 이 데이터 역할은 측정값 필드 또는 합계 필드를 전달할 수 있습니다.

    1. VS Code에서 capabilities.json 파일을 엽니다.

    2. dataRoles 배열 내부의 모든 콘텐츠를 제거합니다.

    3. 다음 코드를 dataRoles 배열에 삽입합니다.

      {
          "displayName": "Measure",
          "name": "measure",
          "kind": "Measure"
      }
      
    4. capabilities.json 파일을 저장합니다.

  • 데이터 뷰 매핑 정의

    dataViewMappings 배열에서 ‘측정값’이라는 필드를 정의합니다. 이 필드를 데이터 역할에 전달할 수 있습니다.

    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": []
}

(선택 사항) 기능 파일 코드 변경 내용 검토

원 카드 시각적 개체가 측정값 필드를 표시하는지 확인하고, 데이터 보기 표시 옵션을 사용하여 변경한 내용을 검토합니다.

  1. Power BI 서비스에서 Power BI 미국 영업 분석 보고서를 엽니다. 다른 보고서를 사용하여 원 카드 시각적 개체를 개발하는 경우 해당 보고서로 이동합니다.

  2. 이제 측정값이라는 필드를 사용하여 원 카드 시각적 개체를 구성할 수 있습니다. 필드 창의 요소를 측정값 필드로 끌어 놓을 수 있습니다.

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

    참고 항목

    시각적 개체 프로젝트에는 아직 데이터 바인딩 논리가 포함되지 않습니다.

  3. 부동 도구 모음에서 데이터 보기 표시를 선택합니다.

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

  4. 세 점을 선택하여 표시를 확장하고, 단일을 선택하여 값을 확인합니다.

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

  5. 메타데이터를 확장하고 배열을 확장한 다음, 형식displayName 값을 검토합니다.

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

  6. 시각적 개체로 다시 토글하려면 시각적 개체 위에서 움직이는 도구 모음에서 데이터 보기 표시를 선택합니다.

데이터를 사용하도록 시각적 개체 구성

지금까지 시각적 개체는 렌더링되지만 데이터를 표시하지는 않습니다. 이 섹션에서는 원 카드 시각적 개체에서 데이터를 사용할 수 있도록 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 시각적 개체를 만들었습니다. 여기에 서식 옵션을 추가하거나 즉시 사용하기 위해 그대로 패키지할 수 있습니다.

다음 단계