juliaplots.jlstatsplots.jl

How to have a customized legend in the x axis when using groupedbar by StatsPlots


As mentioned, I wanted to plot a groupedbar using StatsPlots in Julia. Here is my code:

legends = repeat(["myopic baseline", "vfa", "lvfa", "nnvfa", "nnvfa with attention"], outer=2)
training_time_per_step = [0., 9.817792895793914, 6.380393509864807, 15.770121607780457, 31.79437662124634]
eval_time_per_step = [2.756498346328735, 6.823106627861659, 6.184429474310442, 13.286595929535952, 20.297245191227304]
ctg = repeat(["training time per step", "eval time per step"], inner = 5)
bar1 = groupedbar(legends, vcat(training_time_per_step, eval_time_per_step), group=ctg, xlabel="Methods", ylabel="Time", 
title="Time Evaluation", legend=:topleft, reuse=false)
display(bar1)

I want the legends to have the same order as I defined, but I find it is automatically ordered by the name of each legend: enter image description here

How can I solve this problem?


Solution

  • You need your ctg to be a CategoricalArray rather than a Vector of Strings. Categorical Arrays are maintaining the order of classes and are supported by StatsPlots.

    using CategoricalArrays
    levlabels = ["training time per step", "eval time per step"]
    ctg=CategoricalArray(repeat(levlabels, inner = 5))
    levels!(ctg, levlabels)
    

    Now your labels will not get auto-sorted alphabetically :) (no change to the actual plotting command that you used so I do not copy paste it here).

    enter image description here