Reputation: 12983
I am using JfreeChart 1.0.15 library.
I want to show percentage score of the college and branches, so I used setNumberFormatOverride()
method
final NumberAxis valueAxis = new NumberAxis("Percentage Score");
valueAxis.setNumberFormatOverride(NumberFormat.getPercentInstance());
It is showing me the %
sign on the Y-axis
but all the values are getting multiplied by 100.
See the Y-axis
values. Label values on the bars are correct.
If I divide each value by 100 then Y-axis
values are correct (e.g. 15%,19%,25%,27%) but label values are displaying wrong (e.g. 0.15,0.19,0.25,0.27).
Below code also won't give the desired output
DecimalFormat pctFormat = new DecimalFormat("#.0%");
valueAxis.setNumberFormatOverride(pctFormat);
I tried different solutions from
none of them worked.
If you need more information let me know.
Upvotes: 1
Views: 3723
Reputation: 12983
Thanks @Keppil. I managed to solve from your valuable comment
I was using below code to set label
barPlot.getRenderer().setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
barPlot.getRenderer().setBaseItemLabelsVisible(true);
The mistake was invoking default constructor StandardCategoryItemLabelGenerator()
.
See question labels are not in percent %
format.
I solved by passing NumberFormat
instance pctFormat
to the parameterized constructor StandardCategoryItemLabelGenerator(java.lang.String labelFormat, java.text.NumberFormat formatter)
barPlot.getRenderer().setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}",pctFormat));
barPlot.getRenderer().setBaseItemLabelsVisible(true);
Now format has been applied to the labels also.
Upvotes: 0
Reputation: 5451
If you look at the source for NumberFormat
you'll see that NumberFormat#getPercentInstance()
actually returns a DecimalFormat
instance. Although it's not immediately obvious from the source what format string that instance uses it's safe to assume it contains a %
.
According to the DecimalFormat
javadoc section titled Special Pattern Characters, a %
in a format string means Multiply by 100 and show as percentage
. Luckily NumberFormat
provides a setMultiplier()
method, so you can do this to fix your issue:
DecimalFormat pctFormat = new DecimalFormat("##.0%");
pctFormat.setMultiplier(1);
valueAxis.setNumberFormatOverride(pctFormat);
I believe you can also enquote the %
, like this:
DecimalFormat pctFormat = new DecimalFormat("##.0'%'");
valueAxis.setNumberFormatOverride(pctFormat);
Upvotes: 6