How can I change the series order of the legend in Plots?


#1

When making stacked bar plots or stacked area plots, the default series order in the legend appears upside-down compared to the order in the plot itself. Example using the groupedbar() recipe provided by StatPlots:

using StatPlots
plotly()
groupedbar(rand(10,5), bar_position = :stack, lab=["A" "B" "C" "D" "E"])

newplot%20(3)

The official word is that you can’t currently specify the order, but can someone come up with a hackish solution? I have to make a large number of stacked plots with 10+ series each, and I really don’t want to fix all those legends manually in Photoshop.


#2

I came up with a disgusting little hack myself, I’ll explain it here if anyone else needs something similar.

The idea is to add more bars with dummy data (all zeros) to the plot using 5 (in this case) additional color categories, reusing the same 5 colors but in reverse order, then hide the legend entries for the original data, and finally showing legend entries for the new colors using the original legend labels. Like this:

groupedbar([1:10;12;12], [rand(10,5) zeros(10,5); zeros(2,10)], bar_position = :stack,
        lab=["" "" "" "" "" "A" "B" "C" "D" "E"], color=[1 2 3 4 5 5 4 3 2 1], xlim=(0,11))

newplot%20(4)

Note that I added two new bars with dummy data. Strangely, when I just added one the width of the bars changed a bit. (Why?)

Like I said, a nasty hack, but it’s easy to hide away the ugliness in a function. If anyone else has a better idea then please share.


#3

This is a bug in groupedbar, though. The colors of the bars should be reversed. You could take a look at just fixing the recipe?