Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
ChartUtils è un set di interfacce e metodi per la creazione di assi, etichette dati e legende negli oggetti visivi di Power BI.
Installazione
Per installare il pacchetto, è necessario eseguire il comando seguente nella directory con l'oggetto visivo corrente:
npm install powerbi-visuals-utils-chartutils --save
Helper assi
L'helper assi (oggetto axis nelle utilità) fornisce funzioni per semplificare le manipolazioni che dispongono di un asse.
Il modulo fornisce le funzioni seguenti:
getRecommendedNumberOfTicksForXAxis
Questa funzione restituisce il numero consigliato di segni di graduazione in base alla larghezza del grafico.
function getRecommendedNumberOfTicksForXAxis(availableWidth: number): number;
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
axis.getRecommendedNumberOfTicksForXAxis(1024);
// returns: 8
getRecommendedNumberOfTicksForYAxis
Questa funzione restituisce il numero consigliato di segni di graduazione in base all'altezza del grafico.
function getRecommendedNumberOfTicksForYAxis(availableWidth: number);
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
axis.getRecommendedNumberOfTicksForYAxis(100);
// returns: 3
getBestNumberOfTicks
Restituisce il numero ottimale di segni di graduazione in base al valore minimo, al valore massimo, ai metadati delle misure e al numero massimo di segni di graduazione.
function getBestNumberOfTicks(
min: number,
max: number,
valuesMetadata: DataViewMetadataColumn[],
maxTickCount: number,
isDateTime?: boolean
): number;
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
var dataViewMetadataColumnWithIntegersOnly: powerbi.DataViewMetadataColumn[] = [
{
displayName: "col1",
isMeasure: true,
type: ValueType.fromDescriptor({ integer: true })
},
{
displayName: "col2",
isMeasure: true,
type: ValueType.fromDescriptor({ integer: true })
}
];
var actual = axis.getBestNumberOfTicks(
0,
3,
dataViewMetadataColumnWithIntegersOnly,
6
);
// returns: 4
getTickLabelMargins
Questa funzione restituisce i margini delle etichette dei segni di graduazione.
function getTickLabelMargins(
viewport: IViewport,
yMarginLimit: number,
textWidthMeasurer: ITextAsSVGMeasurer,
textHeightMeasurer: ITextAsSVGMeasurer,
axes: CartesianAxisProperties,
bottomMarginLimit: number,
properties: TextProperties,
scrollbarVisible?: boolean,
showOnRight?: boolean,
renderXAxis?: boolean,
renderY1Axis?: boolean,
renderY2Axis?: boolean
): TickLabelMargins;
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
axis.getTickLabelMargins(
plotArea,
marginLimits.left,
TextMeasurementService.measureSvgTextWidth,
TextMeasurementService.estimateSvgTextHeight,
axes,
marginLimits.bottom,
textProperties,
/*scrolling*/ false,
showY1OnRight,
renderXAxis,
renderY1Axis,
renderY2Axis
);
// returns: xMax, yLeft, yRight, stackHeigh;
isOrdinal
Controlla se una stringa è Null, non definita o vuota.
function isOrdinal(type: ValueTypeDescriptor): boolean;
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
let type = ValueType.fromDescriptor({ misc: { barcode: true } });
axis.isOrdinal(type);
// returns: true
isDateTime
Controlla se un valore è di tipo DateTime.
function isDateTime(type: ValueTypeDescriptor): boolean;
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
axis.isDateTime(ValueType.fromDescriptor({ dateTime: true }));
// returns: true
getCategoryThickness
Usa la scala D3 per ottenere lo spessore effettivo della categoria.
function getCategoryThickness(scale: any): number;
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
let range = [0, 100];
let domain = [0, 10];
let scale = d3.scale
.linear()
.domain(domain)
.range(range);
let actualThickness = axis.getCategoryThickness(scale);
invertOrdinalScale
Questa funzione inverte la scala ordinale. Se x < scale.range()[0], viene restituito scale.domain()[0]. In caso contrario, viene restituito l'elemento più grande in scale.domain() che è < = x.
function invertOrdinalScale(scale: d3.scale.Ordinal<any, any>, x: number);
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
let domain: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
pixelSpan: number = 100,
ordinalScale: d3.scale.ordinal = axis.createOrdinalScale(
pixelSpan,
domain,
0.4
);
axis.invertOrdinalScale(ordinalScale, 49);
// returns: 4
findClosestXAxisIndex
Questa funzione trova e restituisce l'indice dell'asse X più vicino.
function findClosestXAxisIndex(
categoryValue: number,
categoryAxisValues: AxisHelperCategoryDataPoint[]
): number;
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
/**
* Finds the index of the category of the given x coordinate given.
* pointX is in non-scaled screen-space, and offsetX is in render-space.
* offsetX does not need any scaling adjustment.
* @param {number} pointX The mouse coordinate in screen-space, without scaling applied
* @param {number} offsetX Any left offset in d3.scale render-space
* @return {number}
*/
private findIndex(pointX: number, offsetX?: number): number {
// we are using mouse coordinates that do not know about any potential CSS transform scale
let xScale = this.scaleDetector.getScale().x;
if (!Double.equalWithPrecision(xScale, 1.0, 0.00001)) {
pointX = pointX / xScale;
}
if (offsetX) {
pointX += offsetX;
}
let index = axis.invertScale(this.xAxisProperties.scale, pointX);
if (this.data.isScalar) {
// When we have scalar data the inverted scale produces a category value, so we need to search for the closest index.
index = axis.findClosestXAxisIndex(index, this.data.categoryData);
}
return index;
}
diffScaled
Questa funzione calcola e restituisce una differenza dei valori nella scala.
function diffScaled(
scale: d3.scale.Linear<any, any>,
value1: any,
value2: any
): number;
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
var scale: d3.scale.Linear<number, number>,
range = [0, 999],
domain = [0, 1, 2, 3, 4, 5, 6, 7, 8, 999];
scale = d3.scale.linear()
.range(range)
.domain(domain);
return axis.diffScaled(scale, 0, 0));
// returns: 0
createDomain
Questa funzione crea un dominio di valori per un asse.
function createDomain(
data: any[],
axisType: ValueTypeDescriptor,
isScalar: boolean,
forcedScalarDomain: any[],
ensureDomain?: NumberRange
): number[];
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
var cartesianSeries = [
{
data: [
{ categoryValue: 7, value: 11, categoryIndex: 0, seriesIndex: 0 },
{
categoryValue: 9,
value: 9,
categoryIndex: 1,
seriesIndex: 0
},
{
categoryValue: 15,
value: 6,
categoryIndex: 2,
seriesIndex: 0
},
{ categoryValue: 22, value: 7, categoryIndex: 3, seriesIndex: 0 }
]
}
];
var domain = axis.createDomain(
cartesianSeries,
ValueType.fromDescriptor({ text: true }),
false,
[]
);
// returns: [0, 1, 2, 3]
getCategoryValueType
Questa funzione ottiene il ValueType di una colonna di categoria. Il valore predefinito è Text se il tipo non è presente.
function getCategoryValueType(
data: any[],
axisType: ValueTypeDescriptor,
isScalar: boolean,
forcedScalarDomain: any[],
ensureDomain?: NumberRange
): number[];
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
var cartesianSeries = [
{
data: [
{ categoryValue: 7, value: 11, categoryIndex: 0, seriesIndex: 0 },
{
categoryValue: 9,
value: 9,
categoryIndex: 1,
seriesIndex: 0
},
{
categoryValue: 15,
value: 6,
categoryIndex: 2,
seriesIndex: 0
},
{ categoryValue: 22, value: 7, categoryIndex: 3, seriesIndex: 0 }
]
}
];
axis.getCategoryValueType(
cartesianSeries,
ValueType.fromDescriptor({ text: true }),
false,
[]
);
// returns: [0, 1, 2, 3]
createAxis
Questa funzione crea un asse D3, inclusa la scala. Può essere verticale o orizzontale e di tipo data/ora, numerico o testo.
function createAxis(options: CreateAxisOptions): IAxisProperties;
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
import { valueFormatter } from "powerbi-visuals-utils-formattingutils";
// ...
var dataPercent = [0.0, 0.33, 0.49];
var formatStringProp: powerbi.DataViewObjectPropertyIdentifier = {
objectName: "general",
propertyName: "formatString"
};
let metaDataColumnPercent: powerbi.DataViewMetadataColumn = {
displayName: "Column",
type: ValueType.fromDescriptor({ numeric: true }),
objects: {
general: {
formatString: "0 %"
}
}
};
var os = axis.createAxis({
pixelSpan: 100,
dataDomain: [dataPercent[0], dataPercent[2]],
metaDataColumn: metaDataColumnPercent,
formatString: valueFormatter.getFormatString(
metaDataColumnPercent,
formatStringProp
),
outerPadding: 0.5,
isScalar: true,
isVertical: true
});
applyCustomizedDomain
Questa funzione imposta un dominio personalizzato, ma non cambia quando non viene impostato alcun elemento.
function applyCustomizedDomain(customizedDomain: any[], forcedDomain: any[]): any[];
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
let customizedDomain = [undefined, 20],
existingDomain = [0, 10];
axis.applyCustomizedDomain(customizedDomain, existingDomain);
// returns: {0:0, 1:20}
combineDomain
Questa funzione combina il dominio forzato con il dominio effettivo se è stato impostato uno dei valori. forcedDomain ha la priorità. Estende il dominio se richiesto da un punto di riferimento.
function combineDomain(
forcedDomain: any[],
domain: any[],
ensureDomain?: NumberRange
): any[];
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
let forcedYDomain = this.valueAxisProperties
? [this.valueAxisProperties["secStart"], this.valueAxisProperties["secEnd"]]
: null;
let xDomain = [minX, maxX];
axis.combineDomain(forcedYDomain, xDomain, ensureXDomain);
powerOfTen
Questa funzione indica se il numero è una potenza di 10.
function powerOfTen(d: any): boolean;
Esempio:
import { axis } from "powerbi-visuals-utils-chartutils";
// ...
axis.powerOfTen(10);
// returns: true
DataLabelManager
DataLabelManager consente di creare e gestire le etichette. Dispone gli elementi etichetta usando il rettangolo o il punto di ancoraggio. Le collisioni possono essere rilevate automaticamente per riposizionare o nascondere gli elementi.
La classe DataLabelManager fornisce i metodi seguenti:
hideCollidedLabels
Questo metodo modifica la posizione e la visibilità delle etichette nell'area di disegno in base alle dimensioni e alla sovrapposizione delle etichette.
function hideCollidedLabels(
viewport: IViewport,
data: any[],
layout: any,
addTransform: boolean = false
hideCollidedLabels?: boolean
): LabelEnabledDataPoint[];
Esempio:
let dataLabelManager = new DataLabelManager();
let filteredData = dataLabelManager.hideCollidedLabels(
this.viewport,
values,
labelLayout,
true,
true
);
isValid
Questo metodo statico controlla se il rettangolo specificato è valido, se lo è, ha larghezza e altezza positive.
function isValid(rect: IRect): boolean;
Esempio:
let rectangle = {
left: 150,
top: 130,
width: 120,
height: 110
};
DataLabelManager.isValid(rectangle);
// returns: true
DataLabelUtils
DataLabelUtils fornisce utilità per modificare le etichette dati.
Il metodo fornisce le funzioni, le interfacce e le classi seguenti:
getLabelPrecision
Questa funzione calcola la precisione dal formato fornito.
function getLabelPrecision(precision: number, format: string): number;
getLabelFormattedText
Questa funzione restituisce la precisione del formato dal formato fornito.
function getLabelFormattedText(options: LabelFormattedTextOptions): string;
Esempio:
import { dataLabelUtils } from "powerbi-visuals-utils-chartutils";
// ...
let options: LabelFormattedTextOptions = {
text: "some text",
fontFamily: "sans",
fontSize: "15",
fontWeight: "normal"
};
dataLabelUtils.getLabelFormattedText(options);
enumerateDataLabels
Questa funzione restituisce VisualObjectInstance per le etichette dati.
function enumerateDataLabels(
options: VisualDataLabelsSettingsOptions
): VisualObjectInstance;
enumerateCategoryLabels
Questa funzione aggiunge VisualObjectInstance per le etichette dati di categoria a un oggetto enumerazione.
function enumerateCategoryLabels(
enumeration: VisualObjectInstanceEnumerationObject,
dataLabelsSettings: VisualDataLabelsSettings,
withFill: boolean,
isShowCategory: boolean = false,
fontSize?: number
): void;
createColumnFormatterCacheManager
Questa funzione restituisce la Gestione cache, che consente di accedere rapidamente alle etichette formattate.
function createColumnFormatterCacheManager(): IColumnFormatterCacheManager;
Esempio:
import { dataLabelUtils } from "powerbi-visuals-utils-chartutils";
// ...
let value: number = 200000;
labelSettings.displayUnits = 1000000;
labelSettings.precision = 1;
let formattersCache = DataLabelUtils.createColumnFormatterCacheManager();
let formatter = formattersCache.getOrCreate(null, labelSettings);
let formattedValue = formatter.format(value);
// formattedValue == "0.2M"
Servizio Legend
Il servizio Legend fornisce interfacce helper per la creazione e la gestione di legende Power BI per oggetti visivi di Power BI.
Il modulo fornisce le funzioni e le interfacce seguenti:
createLegend
Questa funzione helper semplifica la creazione di legende per oggetti visivi personalizzati di Power BI.
function createLegend(
legendParentElement: HTMLElement, // top visual element, container in which legend will be created
isScrollable: boolean = false, // indicates that legend could be scrollable or not
legendPosition: LegendPosition = LegendPosition.Top // Position of the legend inside of legendParentElement container
): ILegend;
Esempio:
public constructor(options: VisualConstructorOptions) {
this.visualInitOptions = options;
this.layers = [];
var element = this.element = options.element;
var viewport = this.currentViewport = options.viewport;
var hostServices = options.host;
//... some other init calls
this.legend = createLegend(
element,
true);
}
ILegend
Questa interfaccia implementa tutti i metodi necessari per la creazione di legende.
export interface ILegend {
getMargins(): IViewport;
isVisible(): boolean;
changeOrientation(orientation: LegendPosition): void; // processing legend orientation
getOrientation(): LegendPosition; // get information about current legend orientation
drawLegend(data: LegendData, viewport: IViewport); // all legend rendering code is placing here
/**
* Reset the legend by clearing it
*/
reset(): void;
}
drawLegend
Questa funzione misura l'altezza del testo con le proprietà di testo SVG specificate.
function drawLegend(data: LegendData, viewport: IViewport): void;
Esempio:
private renderLegend(): void {
if (!this.isInteractive) {
let legendObjectProperties = this.data.legendObjectProperties;
if (legendObjectProperties) {
let legendData = this.data.legendData;
LegendData.update(legendData, legendObjectProperties);
let position = <string>legendObjectProperties[legendProps.position];
if (position)
this.legend.changeOrientation(LegendPosition[position]);
this.legend.drawLegend(legendData, this.parentViewport);
} else {
this.legend.changeOrientation(LegendPosition.Top);
this.legend.drawLegend({ dataPoints: [] }, this.parentViewport);
}
}
}