How to sort bars on stacked bar style timeseries chart by total value over queried range

The idea is to plot bar per 15 minute which represents count of events during that time per label.
Prometheus can sort only inside each evaluation timestamp so sorting inside query won’t work here as I want stable order for each bar.

Grafana result:

As you can see, the bars are sorted in the alphabetical order by default.

I can sort legend if I change it to table, but that won’t change the bars order on the chart anyway.

For comparison, the same metric visualized in Azure Monitor which by default sort each stacked bar by the order of total count from selected time range:

Stacked bar chart sorted by total number of events in the selected time range seems much easier to reason about.

Is it possible to achieve similar result when using Grafana + Prometheus?

Hi @kamilzzz ,
The Grafana Time Series panel currently doesn’t support sorting stacked bars by total count. The stack order is based on the order Prometheus returns the series, which usually ends up being alphabetical. As far as I could find, there’s no built-in way to change that behavior right now.

So i found a different approach that Instead of using one query that returns all the labels together, I made separate queries for each event type and ordered them manually in the panel. That way grafana keeps the stacks in a consistent order and the chart becomes much easier to read.

If you need anything else, please let me know.

@infofcc3 thanks for idea but I don’t think this is viable solution:

  • adding new label to metric in this case requires to remember to also update queries in Grafana, this alone wouldnt be that bad but the second one:
  • what happens if during selected time range payment is most frequent event but when you change time range to let’s say last day the search event is most frequent one? I guess bar chart will again render unsorted if change dashboard time range to last day.

I tried to use transofrmations to calculate total and sort by it but couldnt come up with working solution.

Hi @kamilzzz,

Currently Grafana’s Time Series visualization does not support dynamically sorting stacked series by total count while still preserving the time-series breakdown. I also tried different transformations. One thing you can try instead is the Bar Chart visualization, where sorting can be achieved using transformations like Reduce and Sort by. However, that behavior is currently limited to the Bar Chart panel only.