Reference visual · full source
Multi-series line chart Power BI custom visual: full source
Cartesian chart with grouped series: an axis field, a legend field and values, with a legend card.
A hand-written reference visual from the VizForge build server, in the same four files the generator writes and built the same way. It was not generated from a prompt, so there is no prompt to show, and no screenshot of it is stored, so none is shown. Files: capabilities.json (57 lines), visual.ts (206 lines), settings.ts (49 lines), style.less (15 lines).
Data roles
| Field well | Role name | Accepts |
|---|---|---|
| Axis | category | Field (grouping) |
| Legend | series | Field (grouping) |
| Values | measure | Measure |
DataView mapping: categorical
Format pane
General (general)
- Show title · Toggle
- Background · Colour picker
Lines (lineStyle)
- Stroke width · Number
- Smooth lines · Toggle
- Show markers · Toggle
Legend (legend)
- Show · Toggle
- Text size · Number
Y axis (yAxis)
- Show · Toggle
- Color · Colour picker
- Text size · Number
Build
- tsc --noEmit
- pass
- pbiviz package
- pass
- pbiviz --certification-audit
- clean
- .pbiviz size
- 29.6 KB
- Build time
- 14 s
Built November 10, 2026with the build server's scripts/build-goldens.sh (powerbi-visuals-tools 7.2.1, TypeScript 5.9.3, powerbi-visuals-api 5.11.1, d3 7.9.0, Node.js 22). Size and time are from that one run.
capabilities.json
Data roles, the DataView mapping and the format-pane objects Power BI reads.
{
"privileges": [],
"dataRoles": [
{ "displayName": "Axis", "name": "category", "kind": "Grouping" },
{ "displayName": "Legend", "name": "series", "kind": "Grouping" },
{ "displayName": "Values", "name": "measure", "kind": "Measure" }
],
"dataViewMappings": [
{
"conditions": [{ "category": { "max": 1 }, "series": { "max": 1 }, "measure": { "min": 1 } }],
"categorical": {
"categories": { "for": { "in": "category" }, "dataReductionAlgorithm": { "top": { "count": 1000 } } },
"values": {
"group": {
"by": "series",
"select": [{ "for": { "in": "measure" } }],
"dataReductionAlgorithm": { "top": { "count": 20 } }
}
}
}
}
],
"objects": {
"general": {
"properties": {
"showTitle": { "type": { "bool": true } },
"backgroundColor": { "type": { "fill": { "solid": { "color": true } } } }
}
},
"lineStyle": {
"properties": {
"strokeWidth": { "type": { "numeric": true } },
"smooth": { "type": { "bool": true } },
"showMarkers": { "type": { "bool": true } }
}
},
"legend": {
"properties": {
"show": { "type": { "bool": true } },
"fontSize": { "type": { "formatting": { "fontSize": true } } }
}
},
"yAxis": {
"properties": {
"show": { "type": { "bool": true } },
"color": { "type": { "fill": { "solid": { "color": true } } } },
"fontSize": { "type": { "formatting": { "fontSize": true } } }
}
}
},
"supportsHighlight": false,
"supportsKeyboardFocus": true,
"supportsMultiVisualSelection": false,
"supportsSynchronizingFilterState": true,
"supportsLandingPage": true,
"sorting": { "default": {} }
}
visual.ts
The IVisual class: constructor, update(), selection, tooltips and the formatting model hook.
"use strict";
import powerbi from "powerbi-visuals-api";
import * as d3 from "d3";
import { FormattingSettingsService } from "powerbi-visuals-utils-formattingmodel";
import { VisualFormattingSettingsModel } from "./settings";
import "./../style/visual.less";
import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions;
import VisualUpdateOptions = powerbi.extensibility.visual.VisualUpdateOptions;
import IVisual = powerbi.extensibility.visual.IVisual;
import IVisualHost = powerbi.extensibility.visual.IVisualHost;
import ISelectionManager = powerbi.extensibility.ISelectionManager;
import ISelectionId = powerbi.visuals.ISelectionId;
import IVisualEventService = powerbi.extensibility.IVisualEventService;
import VisualTooltipDataItem = powerbi.extensibility.VisualTooltipDataItem;
import FormattingModel = powerbi.visuals.FormattingModel;
import DataViewValueColumnGroup = powerbi.DataViewValueColumnGroup;
interface Point {
x: string;
y: number;
series: string;
selectionId: ISelectionId;
}
interface Series {
name: string;
color: string;
points: Point[];
selectionId: ISelectionId;
}
export class Visual implements IVisual {
private host: IVisualHost;
private svg: d3.Selection<any, any, any, any>;
private selectionManager: ISelectionManager;
private events: IVisualEventService;
private formattingSettingsService = new FormattingSettingsService();
private formattingSettings: VisualFormattingSettingsModel = new VisualFormattingSettingsModel();
private series: Series[] = [];
private categories: string[] = [];
constructor(options: VisualConstructorOptions) {
this.host = options.host;
this.events = this.host.eventService;
this.selectionManager = this.host.createSelectionManager();
this.selectionManager.registerOnSelectCallback((ids: powerbi.extensibility.ISelectionId[]) => this.syncSelectionState(ids as ISelectionId[]));
options.element.classList.add("visual-root");
this.svg = d3.select(options.element).append("svg").attr("class", "line-chart");
options.element.addEventListener("contextmenu", (event: MouseEvent) => {
this.selectionManager.showContextMenu({}, { x: event.clientX, y: event.clientY });
event.preventDefault();
});
this.svg.on("click", () => {
if (!this.host.hostCapabilities.allowInteractions) return;
this.selectionManager.clear().then(() => this.syncSelectionState([]));
});
}
public update(options: VisualUpdateOptions): void {
this.events.renderingStarted(options);
try {
const dv = options.dataViews && options.dataViews[0];
const cat = dv?.categorical?.categories?.[0];
const grouped = dv?.categorical?.values?.grouped ? dv.categorical.values.grouped() : [];
if (!dv || !cat || cat.values.length === 0 || grouped.length === 0) {
this.svg.selectAll("*").remove();
this.events.renderingFinished(options);
return;
}
this.formattingSettings = this.formattingSettingsService
.populateFormattingSettingsModel<VisualFormattingSettingsModel>(VisualFormattingSettingsModel, dv);
this.categories = cat.values.map((v) => String(v ?? ""));
const palette = this.host.colorPalette;
this.series = grouped.map((grp: DataViewValueColumnGroup, gi: number) => {
const col = grp.values[0];
const name = grp.name !== undefined ? String(grp.name) : (col?.source?.displayName ?? `Series ${gi + 1}`);
const seriesId = this.host.createSelectionIdBuilder().withSeries(dv.categorical!.values!, grp).createSelectionId();
const points: Point[] = this.categories.map((x, i) => ({
x,
y: Number(col?.values[i] ?? 0) || 0,
series: name,
selectionId: this.host.createSelectionIdBuilder().withCategory(cat, i).withSeries(dv.categorical!.values!, grp).createSelectionId(),
}));
return { name, color: palette.getColor(name).value, points, selectionId: seriesId };
});
const width = Number(options.viewport.width);
const height = Number(options.viewport.height);
if (width < 120 || height < 100) {
this.svg.selectAll("*").remove();
} else {
this.render(width, height);
}
} catch (err) {
console.error("[line_chart] update failed", err);
}
this.events.renderingFinished(options);
}
private render(width: number, height: number): void {
const s = this.formattingSettings;
const showLegend = s.legend.show.value && width >= 250;
const margin = { top: showLegend ? 28 : 12, right: 16, bottom: 36, left: 48 };
const w = Math.max(10, width - margin.left - margin.right);
const h = Math.max(10, height - margin.top - margin.bottom);
this.svg.attr("width", width).attr("height", height).style("background", s.general.backgroundColor.value.value);
this.svg.selectAll("*").remove();
const g = this.svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);
const x = d3.scalePoint<string>().domain(this.categories).range([0, w]);
const all = this.series.flatMap((sr) => sr.points.map((p) => p.y));
const [lo, hi] = all.length > 0 ? (d3.extent(all) as [number, number]) : [0, 1];
const y = d3.scaleLinear().domain([Math.min(0, lo), (hi || 1) * 1.05]).nice().range([h, 0]);
const line = d3.line<Point>()
.x((p) => x(p.x) ?? 0)
.y((p) => y(p.y))
.curve(s.lineStyle.smooth.value ? d3.curveMonotoneX : d3.curveLinear);
g.append("g").attr("transform", `translate(0,${h})`).call(d3.axisBottom(x) as any)
.selectAll("text").text((d: any) => (String(d).length > 15 ? String(d).slice(0, 14) + "…" : String(d)));
if (s.yAxis.show.value) {
g.append("g").call(d3.axisLeft(y).ticks(5) as any)
.selectAll("text").style("font-size", `${s.yAxis.fontSize.value}px`).style("fill", s.yAxis.color.value.value);
}
const strokeWidth = Math.max(0.5, Number(s.lineStyle.strokeWidth.value) || 2);
const paths = g.selectAll<SVGPathElement, Series>("path.series-line").data(this.series).join("path")
.attr("class", "series-line data-element")
.attr("d", (sr) => line(sr.points) as any)
.attr("fill", "none")
.attr("stroke", (sr) => sr.color)
.attr("stroke-width", strokeWidth);
this.bindInteractivity(paths, (sr: Series) => sr.selectionId, (sr: Series) => [{ displayName: "Series", value: sr.name }]);
if (s.lineStyle.showMarkers.value) {
const dots = g.selectAll<SVGCircleElement, Point>("circle.marker")
.data(this.series.flatMap((sr) => sr.points.map((p) => ({ ...p, color: sr.color }))))
.join("circle")
.attr("class", "marker data-element")
.attr("cx", (p) => x(p.x) ?? 0)
.attr("cy", (p) => y(p.y))
.attr("r", 3.5)
.attr("fill", (p: any) => p.color);
this.bindInteractivity(dots, (p: Point) => p.selectionId, (p: Point) => [
{ displayName: "Series", value: p.series },
{ displayName: String(p.x), value: p.y.toLocaleString() },
]);
}
if (showLegend) {
const legend = this.svg.append("g").attr("class", "legend").attr("transform", `translate(${margin.left},10)`);
let offset = 0;
for (const sr of this.series) {
const item = legend.append("g").attr("transform", `translate(${offset},0)`);
item.append("rect").attr("width", 10).attr("height", 10).attr("rx", 2).attr("fill", sr.color);
const label = item.append("text").attr("x", 14).attr("y", 9)
.style("font-size", `${s.legend.fontSize.value}px`).text(sr.name);
offset += 14 + sr.name.length * Number(s.legend.fontSize.value) * 0.6 + 12;
if (offset > w) { label.remove(); item.remove(); break; }
}
}
}
private bindInteractivity(
sel: d3.Selection<any, any, any, any>,
idOf: (d: any) => ISelectionId,
tooltipOf: (d: any) => VisualTooltipDataItem[],
): void {
const allow = this.host.hostCapabilities.allowInteractions;
sel.style("cursor", allow ? "pointer" : "default")
.on("click", (event: MouseEvent, d: any) => {
if (!allow) return;
this.selectionManager.select(idOf(d), event.ctrlKey || event.metaKey)
.then((ids: powerbi.extensibility.ISelectionId[]) => this.syncSelectionState(ids as ISelectionId[]));
event.stopPropagation();
})
.on("contextmenu", (event: MouseEvent, d: any) => {
this.selectionManager.showContextMenu(idOf(d), { x: event.clientX, y: event.clientY });
event.preventDefault();
event.stopPropagation();
})
.on("mouseover", (event: MouseEvent, d: any) => {
this.host.tooltipService.show({ coordinates: [event.clientX, event.clientY], isTouchEvent: false, dataItems: tooltipOf(d), identities: [idOf(d)] });
})
.on("mousemove", (event: MouseEvent) => {
this.host.tooltipService.move({ coordinates: [event.clientX, event.clientY], isTouchEvent: false, dataItems: [], identities: [] });
})
.on("mouseout", () => this.host.tooltipService.hide({ immediately: true, isTouchEvent: false }));
}
private syncSelectionState(ids: ISelectionId[]): void {
const has = ids.length > 0;
this.svg.selectAll<SVGPathElement, Series>("path.series-line")
.style("opacity", (sr) => (!has || ids.some((id) => id.includes(sr.selectionId)) ? 1 : 0.3));
this.svg.selectAll<SVGCircleElement, Point>("circle.marker")
.style("opacity", (p) => (!has || ids.some((id) => id.includes(p.selectionId)) ? 1 : 0.3));
}
public getFormattingModel(): FormattingModel {
return this.formattingSettingsService.buildFormattingModel(this.formattingSettings);
}
}
settings.ts
The formatting model: one card class per format-pane card, each setting a typed slice.
import { formattingSettings } from "powerbi-visuals-utils-formattingmodel";
import FormattingSettingsCard = formattingSettings.SimpleCard;
import FormattingSettingsSlice = formattingSettings.Slice;
import FormattingSettingsModel = formattingSettings.Model;
class GeneralCard extends FormattingSettingsCard {
showTitle = new formattingSettings.ToggleSwitch({ name: "showTitle", displayName: "Show title", value: true });
backgroundColor = new formattingSettings.ColorPicker({ name: "backgroundColor", displayName: "Background", value: { value: "#FFFFFF" } });
name = "general";
displayName = "General";
slices: FormattingSettingsSlice[] = [this.showTitle, this.backgroundColor];
}
class LineStyleCard extends FormattingSettingsCard {
strokeWidth = new formattingSettings.NumUpDown({ name: "strokeWidth", displayName: "Stroke width", value: 2 });
smooth = new formattingSettings.ToggleSwitch({ name: "smooth", displayName: "Smooth lines", value: true });
showMarkers = new formattingSettings.ToggleSwitch({ name: "showMarkers", displayName: "Show markers", value: true });
name = "lineStyle";
displayName = "Lines";
slices: FormattingSettingsSlice[] = [this.strokeWidth, this.smooth, this.showMarkers];
}
class LegendCard extends FormattingSettingsCard {
show = new formattingSettings.ToggleSwitch({ name: "show", displayName: "Show", value: true });
fontSize = new formattingSettings.NumUpDown({ name: "fontSize", displayName: "Text size", value: 10 });
name = "legend";
displayName = "Legend";
topLevelSlice = this.show;
slices: FormattingSettingsSlice[] = [this.fontSize];
}
class YAxisCard extends FormattingSettingsCard {
show = new formattingSettings.ToggleSwitch({ name: "show", displayName: "Show", value: true });
color = new formattingSettings.ColorPicker({ name: "color", displayName: "Color", value: { value: "#605E5C" } });
fontSize = new formattingSettings.NumUpDown({ name: "fontSize", displayName: "Text size", value: 10 });
name = "yAxis";
displayName = "Y axis";
topLevelSlice = this.show;
slices: FormattingSettingsSlice[] = [this.color, this.fontSize];
}
export class VisualFormattingSettingsModel extends FormattingSettingsModel {
general = new GeneralCard();
lineStyle = new LineStyleCard();
legend = new LegendCard();
yAxis = new YAxisCard();
cards: FormattingSettingsCard[] = [this.general, this.lineStyle, this.legend, this.yAxis];
}
style.less
The stylesheet pbiviz compiles into the package.
.visual-root {
width: 100%;
height: 100%;
overflow: hidden;
font-family: "Segoe UI", wf_segoe-ui_normal, helvetica, arial, sans-serif;
svg.line-chart { width: 100%; height: 100%; display: block; }
.series-line, .marker {
transition: opacity 0.15s ease, stroke-width 0.15s ease;
}
.series-line:hover { stroke-width: 4px; }
.marker:hover { r: 5; }
.legend text { fill: #252423; }
}
More examples
- Bar chartCartesian chart on a categorical DataView: one category, one measure, axes, gridlines and data labels.
- Donut chartPart-to-whole chart: per-slice colours, a label-style dropdown and a centre label.
- HeatmapMatrix grid: row and column groupings with a colour scale on the value.
- KPI card with sparklineSingle-value card built in HTML: value, target and a trend sparkline by period.
- TableTable DataView rendered as HTML (no d3): header and row formatting cards.