在Java中,可以使用各種庫來導出圖表。以下是一些建議的庫和步驟:
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.5.0</version>
</dependency>
示例代碼:
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import java.io.File;
public class ChartExporter {
public static void main(String[] args) {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(100, "Series 1", "Category 1");
dataset.addValue(200, "Series 1", "Category 2");
dataset.addValue(300, "Series 2", "Category 1");
dataset.addValue(400, "Series 2", "Category 2");
JFreeChart chart = ChartFactory.createBarChart(
"Bar Chart",
"Category", "Value",
dataset,
PlotOrientation.VERTICAL,
true, true, false
);
try {
ChartUtils.saveChartAsPNG(new File("chart.png"), chart, 800, 600);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>17</version>
</dependency>
示例代碼:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ChartExporter extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
BarChart<String, Number> chart = new BarChart<>();
chart.setTitle("Bar Chart");
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis();
chart.getXAxes().add(xAxis);
chart.getYAxes().add(yAxis);
xAxis.setLabel("Category");
yAxis.setLabel("Value");
chart.getData().add(new BarChart.Data<>("Series 1", 100));
chart.getData().add(new BarChart.Data<>("Series 1", 200));
chart.getData().add(new BarChart.Data<>("Series 2", 300));
chart.getData().add(new BarChart.Data<>("Series 2", 400));
StackPane root = new StackPane();
root.getChildren().add(chart);
Scene scene = new Scene(root, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
}
請注意,這些示例僅展示了如何創建和顯示圖表。要將圖表導出為圖像文件,可以使用Java的圖形2D API或第三方庫(如ImageIO)。