Visualize Your Data with Java: 3 Must-Try Libraries for Stunning Charts

·

4 min read

Data visualization is an essential tool for making sense of complex data sets. In Java, there are several libraries and frameworks that make it easy to create stunning and informative visualizations. In this blog, we explore some of the most popular libraries and frameworks for data visualization in Java and provide code examples to help you get started.

JavaFX Charts:

JavaFX is a popular framework for building desktop applications in Java. It includes a set of built-in charts that can be easily customized and integrated into your applications. Here's an example of a simple line chart:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;

public class LineChartExample 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);

        XYChart.Series series = new XYChart.Series();
        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));

        Scene scene = new Scene(lineChart,800,600);
        lineChart.getData().add(series);

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

In this code example, we create a line chart using JavaFX. We define two number axes for the x and y values, create a LineChart object, and add a series of data points to it. Finally, we create a scene and set it as the stage for our application.

JFreeChart:

JFreeChart is a popular open-source library for creating charts and graphs in Java. It provides a wide range of chart types, including bar charts, line charts, pie charts, and more. Here's an example of a simple bar chart:

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import javax.swing.JFrame;

public class BarChartExample extends JFrame {

    public BarChartExample() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.addValue(23, "Sales", "Jan");
        dataset.addValue(14, "Sales", "Feb");
        dataset.addValue(15, "Sales", "Mar");
        dataset.addValue(24, "Sales", "Apr");

        JFreeChart chart = ChartFactory.createBarChart(
                "Monthly Sales",
                "Month",
                "Sales",
                dataset,
                PlotOrientation.VERTICAL,
                false,
                true,
                false
        );

        ChartPanel panel = new ChartPanel(chart);
        setContentPane(panel);
    }

    public static void main(String[] args) {
        BarChartExample example = new BarChartExample();
        example.setSize(800, 600);
        example.setLocationRelativeTo(null);
        example.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        example.setVisible(true);
    }
}

In this code example, we create a bar chart using JFreeChart. We define a dataset with four data points, create a bar chart object, and customize it with titles and labels. Finally, we create a chart panel and set it as the content pane for our JFrame.

Apache POI:

Apache POI is a Java library for working with Microsoft Office documents, including Excel spreadsheets. It includes a set of classes for creating and formatting charts in Excel. Here's an example of a simple line chart created using Apache POI:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelChartExample {

    public static void main(String[] args) throws IOException {

        // create a new workbook
        XSSFWorkbook workbook = new XSSFWorkbook();

        // create a new sheet
        XSSFSheet sheet = workbook.createSheet("Sales");

        // create some sample data
        Object[][] data = {
                {"Jan", 23},
                {"Feb", 14},
                {"Mar", 15},
                {"Apr", 24},
        };

        // create a new row for each data point
        int rowNum = 0;
        for (Object[] row : data) {
            XSSFRow r = sheet.createRow(rowNum++);
            int colNum = 0;
            for (Object obj : row) {
                XSSFCell cell = r.createCell(colNum++);
                if (obj instanceof String) {
                    cell.setCellValue((String) obj);
                } else if (obj instanceof Integer) {
                    cell.setCellValue((Integer) obj);
                }
            }
        }

        // create a chart and add it to the sheet
        XSSFDrawing drawing = sheet.createDrawingPatriarch();
        XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 4, 0, 10, 15);
        XSSFChart chart = drawing.createChart(anchor);
        XSSFChartLegend legend = chart.getOrCreateLegend();
        legend.setPosition(LegendPosition.TOP_RIGHT);
        XSSFLineChartData dataChart = chart.getChartDataFactory().createLineChartData();

        // define the chart axis
        XSSFChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
        ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
        leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);

        // define the chart data
        XSSFLineChartSeries series = dataChart.addSeries(
                new DataSourcesFromSheet(sheet, new CellRangeAddress(0, 3, 0, 0)),
                new DataSourcesFromSheet(sheet, new CellRangeAddress(0, 3, 1, 1))
        );
        series.setTitle("Sales", chart.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING));

        // add the chart to the sheet
        chart.plot(dataChart, bottomAxis, leftAxis);

        // write the workbook to a file
        try (FileOutputStream fileOut = new FileOutputStream("sales.xlsx")) {
            workbook.write(fileOut);
        }

        // clean up
        workbook.close();
    }
}

In this code example, we create an Excel spreadsheet using Apache POI, populate it with some sample data, and create a line chart based on that data. We define the chart axis, data series, and chart title, and add the chart to the worksheet. Finally, we write the workbook to a file.

Conclusion:

Data visualization is a powerful tool for making sense of complex data sets. In Java, there are several libraries and frameworks available for creating informative and visually appealing charts and graphs. In this blog, we explored some of the most popular options, including JavaFX, JFreeChart, and Apache POI, and provided code examples to help you get started. So the next time you're faced with a data visualization challenge in Java, consider these libraries and see which one works best for your needs. With the right tools and a bit of creativity, you can transform your data into powerful visualizations that communicate your message with clarity and impact.

If you have any questions regarding this blog please feel free to comment or drop me a message directly. You can find more of my blogs at devianinfo.wordpress.com

Did you find this article valuable?

Support Vansa by becoming a sponsor. Any amount is appreciated!