Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Register now to learn Fabric in free live sessions led by the best Microsoft experts. From Apr 16 to May 9, in English and Spanish.

Reply
samuts
Frequent Visitor

pbiviz D3.js library issue

Hello.

 

I'm trying to create a graph using the D3.js library. The need I have is to create a chart with multi bars for each line of my dimension. I found a similar example with what I need on stackoverflow: how-to-draw-multiple-bars-in-a-row-in-a-bar-chart-with-spaces-in-between-with-d3 

 

The image below represents the final result I want to have.

 

samuts_0-1637076078660.png

 

So, I created a new project using Pbiviz to make this graphic available as a new visual for power bi.

For the purpose of initial testing I placed the array with data directly in the constructor of the visual.ts class.

 

However, I came across a situation that does not occur when I use the same code in a simple HTML file. What happens is that in the following code snippet the anonymous function is not recognized.

 

(d) => d

 

samuts_1-1637076620690.png

 

I even managed to do a workaround to make the array data show, but I'm only managing to get the first item of each element.

 

samuts_2-1637076734717.png

 

but I'm not able to iterate correctly because for each line I have 2 or more elements.

 

samuts_3-1637076841514.png

 

This is how it is appearing in the modified version of the original stackoverflow code.

samuts_4-1637077237852.png

 

 

1 - How can I get it to iterate over all the elements of my array and plot more than one rect per line?

2 - Why is the anonymous function not being recognized the way it works in the HTML version? (d) => d

 

 

 

 

 

 

/*
*  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 "core-js/stable";
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 EnumerateVisualObjectInstancesOptions = powerbi.EnumerateVisualObjectInstancesOptions;
import VisualObjectInstance = powerbi.VisualObjectInstance;
import DataView = powerbi.DataView;
import VisualObjectInstanceEnumerationObject = powerbi.VisualObjectInstanceEnumerationObject;
import * as d3 from "d3";
type Selection<T extends d3.BaseType> = d3.Selection<T, any, any, any>;

import { VisualSettings } from "./settings";
export class Visual implements IVisual {
    private target: HTMLElement;
    private updateCount: number;
    private settings: VisualSettings;
    private textNode: Text;
    private svg: Selection<SVGElement>;
    private container: Selection<SVGElement>;
    private rect: Selection<SVGElement>;
    private textValue: Selection<SVGElement>;
    private textLabel: Selection<SVGElement>;

    private barGroups;
    private margin;
    private padding;
    private width;
    private height;
    private barHeight;
    private x;
    private colors;
    private groupElements;

    private visualSettings: VisualSettings;

    constructor(options: VisualConstructorOptions) {

        this.barGroups = [
            [{ min: 0, max: 10 }, { min: 12, max: 15 }],
            [{ min: 10, max: 14 }],
            [{ min: 4, max: 6 }, { min: 8, max: 11 }],
            [{ min: 0, max: 8 }]
        ];

        this.margin = {
            left: 10,
            right: 10,
            top: 10,
            bottom: 40
        };
        this.padding = 2;

        this.width = 500, this.height = 150;
        this.barHeight = this.height / this.barGroups.length;

        // console.log(this.height, this.barHeight, this.barGroups.length);

        this.svg = d3.select(options.element)
            .append('svg')
            .attr('width', this.width + this.margin.left + this.margin.right)
            .attr('height', this.height + this.margin.top + this.margin.bottom);

        var xx = this.x = d3.scaleLinear().rangeRound([0, this.width]);
        var colorsX = this.colors = ['darkred', 'darkgreen', 'darkblue'];

        // The last value is the highest
        this.x.domain([0, d3.max(this.barGroups.map((g) => g[g.length - 1].max))]);

        this.svg.append("g")
            .attr("transform", "translate(" + this.margin.left + "," + (this.height + this.margin.top) + ")")
            .call(d3.axisBottom(this.x))

        const groupElements = this.svg.selectAll('.group')
            .data(this.barGroups)
            .enter()
            .append('g')
            .attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")")
            .classed('group', true);

        // groupElements.each(function (d, i) {

        //     var minValue = d[0].min;
        //     var maxValue = d[0].max;

        //     d3.select(this)
        //         .selectAll(".bar")
        //         .data("2")
        //         .enter()
        //         .append("rect")
        //         .classed("bar", true)
        //         .attr("x", xx(minValue))
        //         .attr("width", xx(maxValue) - xx(minValue))
        //         .attr("y", i * 37.5 + 4)
        //         .attr("height", 37.5 - 2 * 4)
        //         .attr("fill", colorsX[i % colorsX.length]);
        // });


        groupElements.each(function (_, i) {
            d3.select(this)
                .selectAll(".bar")
                .data((d) => d)
                .enter()
                .append("rect")
                .classed("bar", true)
                .attr("x", (d) => xx(d.min))
                .attr("width", (d) => xx(d.max - d.min))
                .attr("y", i * 37.5 + 4)
                .attr("height", 37.5 - 2 * 4)
                .attr("fill", colorsX[i % colorsX.length]);

        });



    }

    public update(options: VisualUpdateOptions) {
        //this.settings = Visual.parseSettings(options && options.dataViews && options.dataViews[0]);
        /*
        console.log('Visual update', options);
        if (this.textNode) {
            this.textNode.textContent = (this.updateCount++).toString();
        }
        */
    }

    private static parseSettings(dataView: DataView): VisualSettings {
        return <VisualSettings>VisualSettings.parse(dataView);
    }

    /**
     * This function gets called for each of the objects defined in the capabilities files and allows you to select which of the
     * objects and properties you want to expose to the users in the property pane.
     *
     */
    public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstance[] | VisualObjectInstanceEnumerationObject {
        const settings: VisualSettings = this.visualSettings || <VisualSettings>VisualSettings.getDefault();
        return VisualSettings.enumerateObjectInstances(settings, options);
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

{
  "name": "visual",
  "description": "default_template_value",
  "repository": {
    "type": "default_template_value",
    "url": "default_template_value"
  },
  "license": "MIT",
  "scripts": {
    "pbiviz": "pbiviz",
    "start": "pbiviz start",
    "package": "pbiviz package",
    "lint": "tslint -c tslint.json -p tsconfig.json"
  },
  "dependencies": {
    "@babel/runtime": "7.6.0",
    "@babel/runtime-corejs2": "7.6.0",
    "@types/d3": "5.7.2",
    "core-js": "3.2.1",
    "d3": "5.12.0",
    "powerbi-visuals-api": "~3.8.0",
    "powerbi-visuals-utils-dataviewutils": "2.2.1"
  },
  "devDependencies": {
    "ts-loader": "6.1.0",
    "tslint": "^5.18.0",
    "tslint-microsoft-contrib": "^6.2.0",
    "typescript": "3.6.3"
  }
}

 

 

 

 

 

 

 

Thank you very much in advance.

Samuel

1 ACCEPTED SOLUTION
dm-p
Super User
Super User

Hi @samuts,

Your issue is that you can't always lift and shift JS code to TypeScript without declaring types for things like variables and class properties - the error points at this:

dmp_0-1637879533764.png

You need to specify a structure for barGroups. The ideal way is to declare an interface for your inner data points, e.g.:

interface IDataPoint {
    min: number;
    max: number;
}

Next, you need to give type your barGroups property in your class declaration. As each 'row' is a nested array of the above interface you'd type this as follows:

private barGroups : IDataPoint[][];

You then need to specify how d3 needs to type your data so its structure is known when binding to the DOM. The easiest way to do this is in the initial .data() chain as below:

groupElements.each(function (_, i) {
    d3.select(this)
        .selectAll(".bar")
        .data((d: IDataPoint[]) => d)  // <---- changes made here
        .enter()
        .append("rect")
        .classed("bar", true)
        .attr("x", (d) => xx(d.min))
        .attr("width", (d) => xx(d.max - d.min))
        .attr("y", i * 37.5 + 4)
        .attr("height", 37.5 - 2 * 4)
        .attr("fill", colorsX[i % colorsX.length]);

});

Here's my results when I run the visual:

dmp_2-1637880328580.png

Hopefully this gets you moving in the right direction. Good luck!

Daniel





Did I answer your question? Mark my post as a solution!

Proud to be a Super User!


My course: Introduction to Developing Power BI Visuals


On how to ask a technical question, if you really want an answer (courtesy of SQLBI)




View solution in original post

2 REPLIES 2
dm-p
Super User
Super User

Hi @samuts,

Your issue is that you can't always lift and shift JS code to TypeScript without declaring types for things like variables and class properties - the error points at this:

dmp_0-1637879533764.png

You need to specify a structure for barGroups. The ideal way is to declare an interface for your inner data points, e.g.:

interface IDataPoint {
    min: number;
    max: number;
}

Next, you need to give type your barGroups property in your class declaration. As each 'row' is a nested array of the above interface you'd type this as follows:

private barGroups : IDataPoint[][];

You then need to specify how d3 needs to type your data so its structure is known when binding to the DOM. The easiest way to do this is in the initial .data() chain as below:

groupElements.each(function (_, i) {
    d3.select(this)
        .selectAll(".bar")
        .data((d: IDataPoint[]) => d)  // <---- changes made here
        .enter()
        .append("rect")
        .classed("bar", true)
        .attr("x", (d) => xx(d.min))
        .attr("width", (d) => xx(d.max - d.min))
        .attr("y", i * 37.5 + 4)
        .attr("height", 37.5 - 2 * 4)
        .attr("fill", colorsX[i % colorsX.length]);

});

Here's my results when I run the visual:

dmp_2-1637880328580.png

Hopefully this gets you moving in the right direction. Good luck!

Daniel





Did I answer your question? Mark my post as a solution!

Proud to be a Super User!


My course: Introduction to Developing Power BI Visuals


On how to ask a technical question, if you really want an answer (courtesy of SQLBI)




samuts
Frequent Visitor

Hi Daniel!

 

Thank you very much for your time and for the great explanation of the solution!
🙂

Helpful resources

Announcements
Microsoft Fabric Learn Together

Microsoft Fabric Learn Together

Covering the world! 9:00-10:30 AM Sydney, 4:00-5:30 PM CET (Paris/Berlin), 7:00-8:30 PM Mexico City

PBI_APRIL_CAROUSEL1

Power BI Monthly Update - April 2024

Check out the April 2024 Power BI update to learn about new features.

April Fabric Community Update

Fabric Community Update - April 2024

Find out what's new and trending in the Fabric Community.