X-axis label sort order in d-vl

I’m trying to enforce a specific x-axis sort order in a vega-lite stacked bar chart. I’ve tried a ton of different specifications, but, apparently, I’m missing something each time as the sort order is always alphabetical.

The measure name and sort order are sourced from:

MeasuresTable = 
DATATABLE(
    "Measure", STRING,
    "SortOrder", INTEGER,
    {
        { "Sum Sales", 4 },
        { "Sales Audio", 3 },
        { "Sales Computers", 2 },
        { "Sales Gold Products", 1 }
    }
)

and the value is based on this measure:

SelectedMeasureValue = 
SWITCH(
    TRUE(),
    SELECTEDVALUE(MeasuresTable[Measure]) = "Sum Sales", [Sum Sales],
    SELECTEDVALUE(MeasuresTable[Measure]) = "Sales Audio", [Sales Audio],
    SELECTEDVALUE(MeasuresTable[Measure]) = "Sales Computers", [Sales Computers],
    SELECTEDVALUE(MeasuresTable[Measure]) = "Sales Gold Products", [Sales Gold Products],
    BLANK()
)

Some of the complexity is due to sourcing x-axis labels from a measure—something that can’t be done in core visuals, and the reason for that is that in real life my x-axis labels are derived by concatenating multiple measure values in a string. I’ve skipped that step in the attached example.

Thanks in advance!

stacked-bar-sample.pbix (2.8 MB)

Hi @HufferD

Vega-Lite does not always respect an axis sort order and uses its default of alphabetical. When this impacts me, the workaround I’ve applied successfully is to:

  • add a [calculate] transform that creates a new field by adding a padded prefix to the field in question
  • change the axis encoding to use new field
  • added [axis/labelExpr] to display the new field with the prefix removed

Here’s what I came up with:

Here’s the transform I added:

{
  "calculate": "pad( datum['SortOrder'], 2, '0', 'left' ) + '-' + datum['Measure']",
  "as": "_measure_label_sorted"
}

Here’s the modified encoding I used:

"x": {
  "field": "_measure_label_sorted",
  "type": "nominal",
  "axis": {
	"title": null,
	"labelAngle": 0,
	"labelExpr": "slice( datum.value, 3, 100 )",
	"ticks": false,
	"domain": false
  }
}

Hope it helps.

Greg
eDNA Forum - X-axis label sort order in Deneb using Vega-Lite.pbix (2.8 MB)

1 Like

@Greg,

Thank you very much. I won’t share how many times I tried to do this. Your solution is creative.

You can either specify a manual sort order for the encoding channel, or assign a field value to it (e.g. a number) if you have that and the axis will respect this. Here’s the doc on specifying a sort order, with the various options.

Note that Power BI doesn’t supply a sort order value for any columns that use another field for sorting, so this needs to be manually added to the dataset and this can be used in one of the options above to respect that particular order.

1 Like