如何在 JavaFX 折線圖中將 X 軸移至頂部?


內聯圖表,其中資料值以一系列透過線連線的點表示。在 JavaFX 中,可以透過例項化 javafx.scene.chart.LineChart 類來建立折線圖。

預設情況下,

  • JavaFX 折線圖包含指示 X 軸上資料值中的符號。通常是小的圓圈。

  • 圖中的 X 軸在底部。

  • Y 軸在左側。

將 X 軸移至頂部

Axis 類(所有軸的超類)有一個名為 side 的屬性,它指定你需要當前軸在的繪圖一側(左、右、上、下)。可以使用 setSide() 方法為該屬性設定值。此方法接受以下值之一作為引數 −

  • Side.BOTTOM

  • Side.TOP

  • Side.LEFT

  • Side.RIGHT

要將 X 軸移至頂部,請透過將 Side.TOP 值作為引數傳入你的繪圖的 X 軸物件的 setSide() 方法來呼叫該方法。

示例

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.StackPane;
public class LineChartAxisShift extends Application {
   public void start(Stage stage) {
      //Defining the x an y axes
      CategoryAxis xAxis = new CategoryAxis();
      NumberAxis yAxis = new NumberAxis();
      //Setting labels for the axes
      xAxis.setLabel("Months");
      yAxis.setLabel("Rainfall (mm)");
      //Creating a line chart
      LineChart linechart = new LineChart(xAxis, yAxis);
      //Preparing the data points for the line1
      XYChart.Series series = new XYChart.Series();
      series.getData().add(new XYChart.Data("Jul", 169.9));
      series.getData().add(new XYChart.Data("Aug", 178.7));
      series.getData().add(new XYChart.Data("Sep", 158.3));
      series.getData().add(new XYChart.Data("Oct", 97.2));
      series.getData().add(new XYChart.Data("Nov", 22.4));
      series.getData().add(new XYChart.Data("Dec", 5.9));
      //Setting the name to the line (series)
      series.setName("Rainfall In Hyderabad");
      //Setting the data to Line chart
      linechart.getData().add(series);
      //Shifting the X-axis
      xAxis.setSide(Side.TOP);
      //Creating a stack pane to hold the chart
      StackPane pane = new StackPane(linechart);
      pane.setPadding(new Insets(15, 15, 15, 15));
      pane.setStyle("-fx-background-color: BEIGE");
      //Setting the Scene
      Scene scene = new Scene(pane, 595, 350);
      stage.setTitle("Line Chart");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於: 2020 年 5 月 20 日

380 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.