我试图弄清楚如何根据乘数动态格式化折线图轴上的值。
我将 LogAxis 用于 X 轴和 Y 轴,如下所示:
final LogAxis rangeAxis = new LogAxis(valueAxisLabel);
rangeAxis.setStandardTickUnits(LogAxis.createLogTickUnits(Locale.ENGLISH));
rangeAxis.setRange(0.01, 10.0); //10 mOhms to 10 Ohms
plot.setRangeAxis(rangeAxis);
final LogAxis domainAxis = new LogAxis(frequencyAxisLabel);
domainAxis.setStandardTickUnits(LogAxis.createLogTickUnits(Locale.ENGLISH));
domainAxis.setRange(100, 10000000); //100Hz to 10MHz
plot.setDomainAxis(domainAxis);
我目前在 Y 轴上有以下值:
0.01、0.1、1、10
但希望它显示为
10mOhm、100mOhm、1Ohm、10Ohm
在 X 轴上,我有
100、1,000、10,000、100,000、1,000,000、10,000,000
但希望看到
100Hz、1kHz、10kHz、100kHz、1MHz、10MHz
我知道您可以覆盖NumberFormat
轴上的 used,但我还没有找到一种方法来NumberFormat
根据这样的值动态覆盖 。这可能吗?我需要扩展NumberFormat
才能做到这一点吗?
编辑:根据接受的答案,我扩展NumberFormat
如下(请注意,实施并不完整,而是为了我老板的快速演示目的而被黑客入侵)
public class UnitNumberFormat extends NumberFormat
{
/**
*
*/
private static final long serialVersionUID = -8544764432101798895L;
private UnitValue unitValue;
public UnitNumberFormat(UnitValue unitValue)
{
super();
this.unitValue = unitValue;
}
/*
* (non-Javadoc)
* @see java.text.NumberFormat#format(double, java.lang.StringBuffer,
* java.text.FieldPosition)
*/
@Override
public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos)
{
StringBuffer formattedValue = new StringBuffer();
BigDecimal bd = new BigDecimal(number);
BigDecimal multiplier = new BigDecimal(1);
String multiplierString = "";
if(number < 1 && number > 0)
{
multiplier = new BigDecimal(1000);
multiplierString = "m";
}
else if(number < 1000 && number >= 1)
{
multiplier = new BigDecimal(1);
multiplierString = "";
}
else if(number < 1000000 && number >= 1000)
{
multiplier = new BigDecimal(1. / 1000);
multiplierString = "k";
}
else if(number < 1000000000 && number >= 1000000)
{
multiplier = new BigDecimal(1. / 1000000);
multiplierString = "M";
}
else
{
throw new NumberFormatException("This formatter doesn't yet support values beyond Mega");
}
bd = bd.multiply(multiplier).round(new MathContext(1, RoundingMode.HALF_UP));
formattedValue.append(bd.toPlainString());
formattedValue.append(" ");
formattedValue.append(multiplierString);
formattedValue.append(this.unitValue.getUnit());
return formattedValue;
}
/*
* (non-Javadoc)
* @see java.text.NumberFormat#format(long, java.lang.StringBuffer,
* java.text.FieldPosition)
*/
@Override
public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos)
{
return null;
}
/*
* (non-Javadoc)
* @see java.text.NumberFormat#parse(java.lang.String,
* java.text.ParsePosition)
*/
@Override
public Number parse(String source, ParsePosition parsePosition)
{
return null;
}
}
如下UnitValue
:
public enum UnitValue {
HERTZ("Hz"),
OHMS("Ω"),
;
private final String unit;
private UnitValue(String unit)
{
this.unit = unit;
}
/**
* @return the unit
*/
public String getUnit()
{
return unit;
}
}