教程:创建 R 驱动的 Power BI 视觉对象

作为开发人员,你可以创建自己的 Power BI 视觉对象。 这些视觉对象可供你、你的组织或第三方使用。

本文将分步指导如何创建 R 驱动的 Power BI 视觉对象。

在本教程中,了解如何:

  • 创建 R 驱动的视觉对象
  • 在 Power BI Desktop 中编辑 R 脚本
  • 向视觉对象的依赖项文件添加库
  • 添加静态属性

先决条件

入门

  1. 准备视觉对象的一些示例数据。 可以将这些值保存到 Excel 数据库或 .csv 文件中,然后将其导入到 Power BI Desktop 中。

    MonthNo 总单位数
    1 2303
    2 2319
    3 1732
    4 1615
    5 1427
    6 2253
    7 1147
    8 1515
    9 2516
    10 3131
    11 3170
    12 2762
  2. 若要创建视觉对象,请打开 PowerShell 或终端,并运行以下命令 :

    pbiviz new rVisualSample -t rvisual
    

    此命令为 rVisualSample 视觉对象创建一个新文件夹。 结构基于 rvisual 模板。 它将在视觉对象的根文件夹中创建一个名为 script.r 的文件。 此文件将保管 R 脚本,该脚本运行后可在呈现视觉对象时生成图像。 可以在 Power BI Desktop 中创建 R 脚本。

  3. 从新创建的 rVisualSample 目录运行以下命令:

    pbiviz start
    
  4. 在 Power BI Desktop 中,选择“R 脚本视觉对象” :

    Screenshot of the R script visual control in the Power BI Desktop.

  5. 通过将“月份”和“单位总数”拖动到视觉对象的“值”中,将数据分配到开发人员的视觉对象中 。

    Screenshot showing where to add data to values.

  6. 将“单位总数”的聚合类型设置为“不汇总”。

    Screenshot of menu with option for not summarizing data.

  7. 在 Power BI Desktop 中的 R 脚本编辑器中,键入以下内容:

    plot(dataset)
    

    此命令使用语义模型中的值作为输入来创建散点图。

  8. 选择“运行脚本”图标以查看结果。

    Screenshot of R visual chart with data.

编辑 R 脚本

可以修改 R 脚本来创建其他类型的视觉对象。 接下来创建一个折线图。

  1. 将以下 R 代码粘贴到 R 脚本编辑器中

    x <- dataset[,1] # get the first column from semantic model
    y <- dataset[,2] # get the second column from semantic model
    
    columnNames = colnames(dataset) # get column names
    
    plot(x, y, type="n", xlab=columnNames[1], ylab=columnNames[2]) # draw empty plot with axis and labels only
    lines(x, y, col="green") # draw line plot
    
  2. 选择“运行脚本”图标以查看结果。

    Screenshot of the result of running the script, which is a line plot.

  3. R 脚本准备就绪后,将其复制到视觉对象项目的根目录中的 script.r 文件中。

  4. 在 capabilities.json 文件中,将 dataRoles: name 更改为 dataset,将 dataViewMappings 输入设置为 dataset 。

    {
      "dataRoles": [
        {
          "displayName": "Values",
          "kind": "GroupingOrMeasure",
          "name": "dataset"
        }
      ],
      "dataViewMappings": [
        {
          "scriptResult": {
            "dataInput": {
              "table": {
                "rows": {
                  "select": [
                    {
                      "for": {
                        "in": "dataset"
                      }
                    }
                  ],
                  "dataReductionAlgorithm": {
                    "top": {}
                  }
                }
              }
            },
            ...
          }
        }
      ],
    }
    
  5. 添加以下代码,以支持从 src/visual. ts 文件中调整此映像大小。

      public onResizing(finalViewport: IViewport): void {
          this.imageDiv.style.height = finalViewport.height + "px";
          this.imageDiv.style.width = finalViewport.width + "px";
          this.imageElement.style.height = finalViewport.height + "px";
          this.imageElement.style.width = finalViewport.width + "px";
      }
    

向视觉对象包添加库

corrplot 包创建相关矩阵的图形显示。 有关 corrplot 的详细信息,请参阅 corrplot 包简介

  1. corrplot 库依赖项添加到 dependencies.json 文件。 下面是文件内容示例:

    {
      "cranPackages": [
        {
          "name": "corrplot",
          "displayName": "corrplot",
          "url": "https://cran.r-project.org/web/packages/corrplot/"
        }
      ]
    }
    
  2. 现在可以开始在 script.r 文件中使用 corrplot 包。

    library(corrplot)
    corr <- cor(dataset)
    corrplot(corr, method="circle", order = "hclust")
    

    使用 corrplot 包的结果如下例所示:

    Screenshot of the visualization pane with four ovals created by corrplot.

将静态属性添加到“属性”窗格

现在已有一个基本的 corrplot 视觉对象,接下来将属性添加到“属性”窗格,让用户能够更改对视觉对象的观感。

我们将使用 method 参数来配置数据点的形状。 默认脚本使用圆圈。 修改视觉对象,允许用户在多个选项之间进行选择。

  1. 在 capabilities.json 文件中定义名为 settings 的 object,并向其赋予以下属性

    "settings": {
      "properties": {
        "method": {
          "type": {
            "enumeration": [
              { "value": "circle" },
              { "value": "square" },
              { "value": "ellipse" },
              { "value": "number" },
              { "value": "shade" },
              { "value": "color" },
              { "value": "pie" }
            ]
          }
        }
      }
    }
    
  2. 打开 src/settings.ts 文件。 使用公共属性 methodnamedisplayNameslices 创建一个 VisualCardSettings 类,代码框中所示。

    import ItemDropdown = formattingSettings.ItemDropdown;
    
    const methodOptions = [
        {
            displayName: "Circle",
            value: "circle"
        },
        {
            displayName: "Square",
            value: "square"
        },
        {
            displayName: "Ellipse",
            value: "ellipse"
        },
        {
            displayName: "Number",
            value: "number"
        },
        {
            displayName: "Shade",
            value: "shade"
        },
        {
            displayName: "Color",
            value: "color"
        },
        {
            displayName: "Pie",
            value: "pie"
        }
    ]
    
    class VisualCardSettings extends FormattingSettingsCard {
        method: FormattingSettingsSlice = new ItemDropdown({
            name: "method",
            displayName: "Method",
            items: methodOptions,
            value: methodOptions[0]
        });
    
        name: string = "settings";
        displayName: string = "Settings";
        slices: Array<FormattingSettingsSlice> = [this.method];
    }
    

    完成这些步骤后,可以更改视觉对象的属性。

    Screenshot of R visual settings.

    最后,R 脚本必须具有默认属性。 如果用户不更改属性值(在本例中为形状设置),视觉对象将使用此值。

    对于属性的 R 运行时变量,命名约定为 <objectname>_<propertyname>,在本例中为 settings_method

  3. 运行以下 R 脚本:

    library(corrplot)
    corr <- cor(dataset)
    
    if (!exists("settings_method"))
    {
        settings_method = "circle";
    }
    
    corrplot(corr, method=settings_method, order = "hclust")
    

打包并导入视觉对象

现在可以打包视觉对象,将其导入到任何 Power BI 报表。

  1. 填写 pbivis.json 文件中的 displayNamesupportUrldescription、作者的 nameemail 以及任何其他重要信息。

  2. 如果要更改可视化效果窗格上的视觉对象图标,请替换 assets 文件夹中的 icon.png 文件 。

  3. 从视觉对象的根目录,运行以下命令:

    pbiviz package
    

    有关打包视觉对象的详细信息,请参阅打包自定义视觉对象

  4. 将视觉对象的 pbiviz 文件导入任何 Power BI 报表。 有关如何执行此操作的说明,请参阅将视觉对象文件从本地计算机导入 Power BI

  5. 最终的视觉对象如以下示例所示:

Screenshot of R visual settings with changed value.