Sort a visual by a target data field
In Power BI, you can change how a visual looks by sorting it by different data fields. By changing how you sort a visual, you can highlight the information you want to convey. Whether you're using numeric data (such as sales figures) or text data (such as state names), you can sort your visuals as desired. Power BI provides lots of flexibility for sorting, and quick menus for you to use. To learn more, see Change how a chart is sorted in a Power BI report
You can use the visual.sortBy
API to change how you sort a visual by one of its data fields. You can also control the direction of the sort.
How to sort a visual
The Power BI Client VisualDescriptor class defines a sortBy
method as:
visual.sortBy(request: ISortByVisualRequest): Promise<void>
The ISortByVisualRequest
interface includes a definition for the sort request:
export interface ISortByVisualRequest {
orderBy: ITarget;
direction: SortDirection;
}
orderBy, the target data field of the sort. Data fields that the visual can be sorted by, are found in the visual’s option menu under the Sort by menu command, Learn more about Use targets to select which data field to act on.
direction, the direction of the sort. The
SortDirection
enum defines the sort direction asAscending
orDescending
.enum SortDirection { Ascending = 1, Descending = 2, }
Example
To get the pages of a report, find the active page, and get the visuals. The visual is found with the unique name VisualContainer1
and sorted descending by Total Category Volume
measure on the SalesFact
table:
let pages = await report.getPages();
// Retrieve active page
var activePage = pages.find(function (page) { return page.isActive });
let visuals = await activePage.getVisuals();
// Retrieve target visual (replace "VisualContainer1" with requested visual name)
var visual = visuals.find(function (visual) { return visual.name === "VisualContainer1" });
const request = {
// Set the target data field of the sort
orderBy: {
table: "SalesFact",
measure: "Total Category Volume"
},
direction: models.SortDirection.Descending
};
await visual.sortBy(request);
To sort a visual by a column target:
const request = {
// Set the target data field of the sort
orderBy: {
table: "Store",
column: "Name"
},
direction: models.SortDirection.Ascending
};
await visual.sortBy(request);