为 JFreeChart 动态格式化带小数的轴

Formatting axis with decimals dynamically for JFreeChart

我正在尝试格式化我正在创建的图表的 y 轴 (JFreeCharts)

DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(5); 
numberTickUnit = new NumberTickUnit(numberTickUnit.getSize(), df);

有些图表的范围是 0-15,所以我希望数字有 2 位小数。有些图表的范围从 0.001 到 0.002,所以我希望数字有 5 位小数。

上面的代码运行良好,有 1 个问题。我希望轴上的所有数字都具有相同的格式(最大小数位数)。所以如果我有 0.01251, 0.02000, 0.27490,我希望它像那样显示,而不是 0.01251, 0.02, 0.2749。如何使整个轴具有相同的格式,而不是为每个数字单独设置。

I want the numbers to have 5 decimals.

使用setMinimumFractionDigits(),即"Sets the minimum number of digits allowed in the fraction portion of a number."

XYPlot plot =  (XYPlot) chart.getPlot();
NumberAxis range = (NumberAxis) plot.getRangeAxis();
NumberFormat formatter = DecimalFormat.getInstance();
formatter.setMinimumFractionDigits(5);
range.setNumberFormatOverride(formatter);

我不得不手动完成。

static NavigableMap<Double, String> decimalFormatMap = new TreeMap<Double, String>();
static
{
    decimalFormatMap.put(0.00001, "0.000001");
    decimalFormatMap.put(0.0001, "0.00001");
    decimalFormatMap.put(0.001, "0.0001");
    decimalFormatMap.put(0.01, "0.001");
    decimalFormatMap.put(0.1, "0.01");
    decimalFormatMap.put(1.0, "0.1");
    decimalFormatMap.put(100.0, "1");
}
NumberTickUnit numberTickUnit = * some key number *;
String decimalFormat = decimalFormatMap.get(
    decimalFormatMap.floorKey(numberTickUnit.getSize()));