如何在Julia的StatsPlots groupedbar中自定义X轴图例顺序
问题:StatsPlots groupedbar图例自动排序,如何保持自定义顺序?
使用Julia的StatsPlots绘制分组柱状图时,图例会按名称自动排序,无法保持自定义顺序,代码如下:
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)
希望图例保持["training time per step", "eval time per step"]的定义顺序,而非自动排序后的结果。
解决方案
StatsPlots默认会对分组变量按字典序排序,要保留自定义顺序,需将分组变量ctg转换为有序分类类型,并指定目标顺序。具体实现:
- 导入
CategoricalArrays包(未安装先执行using Pkg; Pkg.add("CategoricalArrays")) - 用
CategoricalArray创建有序分类,通过levels参数指定图例顺序,同时设置ordered=true
修改后的完整代码:
using StatsPlots using CategoricalArrays # 定义方法名称和时间数据 method_names = ["myopic baseline", "vfa", "lvfa", "nnvfa", "nnvfa with attention"] 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_order = ["training time per step", "eval time per step"] ctg = repeat(CategoricalArray(ctg_order, ordered=true), inner=5) # 构造x轴标签 legends = repeat(method_names, outer=2) # 绘制分组柱状图 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)
处理后,图例将严格按照定义的["training time per step", "eval time per step"]顺序显示,不会再自动排序。
内容的提问来源于stack exchange,提问作者PokeLu
相关产品推荐
相关产品推荐

