'How can I order columns in a box chart in JFreeChart?

I have a box chart with multiple boxes in rows and columns. The ordering of the boxes is wrong. Each row (color) is labeled by an enum constant of type Multiple, and each column (group) is labeled by an enum constant of type Type. (The real names of the types are different; This is simplified.)

The code to generate the chart is like this, but this has many things omitted because I think that they are not important:

var results; // results are predefined
var dataset = new DefaultBoxAndWhiskerCategoryDataset();

for (Type type : results.keySet()) { // type is an enum constant
    var innerResults = results.get(type);
    for (Multiple multiple : innerResults.keySet()) { // multiple is an enum constant
        List<Double> values; // calculate values here
        dataset.add(values, multiple, type);
} }

var chart = ChartFactory.createBoxAndWhiskerChart(
    "",
    "type",
    "",
    dataset,
    true
);

This is the resulting chart:

box chart with wrongly ordered columns

The order of the multiples is supposed to be ascending (“0.25”, “0.5”, …). The order of the types is supposed to be “hard MW”, “soft MW”, “multiple-overlay MW”. That is how they are declared in the source code, so that is how they are ordered according to compareTo. I didn't find that JFreeChart would have a documented ordering for rows and columns, but that is how I expect it.

Why are the boxes in this order and not the expected one? How can I force JFreeChart to sort the rows and columns how I expect it? I have no idea what causes this; I have a very similar chart, but the order there is correct.



Solution 1:[1]

Summarizing our colloquy, your dataset row and column keys are held by an Enum, which implements Comparable. In particular, "The natural order implemented by this method is the order in which the constants are declared." However, because the values come from a keySet() held by the enum, they are generally unordered. While it may be possible to substitute a SortedSet, you have chosen to sort each set explicitly:

keySet().stream().sorted().toList()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 trashgod