从轴中删除负值

时间:2015-03-15 16:33:20

标签: java javafx-8 bar-chart linechart axis-labels

我有BarChartLineChart

可能的值从负( - )变为正(+)。我怎么才显示正轴标签?正如只删除数字一样。

我应该制作自定义图表还是有更简单的方法?

2 个答案:

答案 0 :(得分:3)

您可以将Y轴下限设置为0并禁用自动量程:

    yAxis.setAutoRanging(false);
    yAxis.setLowerBound(0);

以下是一个例子:

chart

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();
    }
}

答案 1 :(得分:2)

在查看NumberAxis源代码后,我发现NumberAxis类中的DefaultFormatter类对此负责。所以覆盖它的toString方法就足够了。

myAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(neerslagAxis) {
            @Override
            public String toString(Number object) {
                if ((double) object < 0) {
                    return "";
                } else {
                    return ("" + object).replace(".0", "");
                }
            }
        });