I have a BarChart
and a LineChart
.
The possible values go from negative(-) to positive(+). How would I only display the positive axis-labels? As in only remove the numbers.
Should I make a custom Chart or is there an easier way?
You can set Y-Axis lower bound to 0 and disable an auto-ranging:
yAxis.setAutoRanging(false);
yAxis.setLowerBound(0);
Here is an example:
public class FXChart extends Application {
@Override
public void start(Stage stage) {
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
final LineChart<Number, Number> lineChart
= new LineChart<>(xAxis, yAxis);
//defining a series
XYChart.Series series = new XYChart.Series();
series.setName("My portfolio");
//populating the series with data
series.getData().add(new XYChart.Data(1, 23));
series.getData().add(new XYChart.Data(2, -14));
series.getData().add(new XYChart.Data(3, 15));
series.getData().add(new XYChart.Data(4, -24));
series.getData().add(new XYChart.Data(5, 34));
series.getData().add(new XYChart.Data(6, -36));
series.getData().add(new XYChart.Data(7, 22));
series.getData().add(new XYChart.Data(8, -45));
series.getData().add(new XYChart.Data(9, 43));
series.getData().add(new XYChart.Data(10, -17));
series.getData().add(new XYChart.Data(11, 29));
series.getData().add(new XYChart.Data(12, 25));
yAxis.setAutoRanging(false);
yAxis.setLowerBound(0);
Scene scene = new Scene(lineChart, 800, 600);
lineChart.getData().add(series);
stage.setScene(scene);
stage.show();
}
}
After looking through the NumberAxis source, I found out that the DefaultFormatter class inside the NumberAxis class is accountable for this. So overriding the toString method of it was enough.
myAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(neerslagAxis) {
@Override
public String toString(Number object) {
if ((double) object < 0) {
return "";
} else {
return ("" + object).replace(".0", "");
}
}
});