Guide to JFreeChart Library in Java

Introduction to JFreeChart

JFreeChart is a popular open-source chart library for the Java programming language. It provides a wide range of chart types, including bar charts, pie charts, line charts, and more. JFreeChart is highly customizable and supports interactive features, making it a powerful tool for visualizing data in Java applications.

Installation

Adding JFreeChart to Your Project

To use JFreeChart, add the following dependency to your pom.xml if you're using Maven:

<dependency>
    <groupId>org.jfree</groupId>
    <artifactId>jfreechart</artifactId>
    <version>1.5.3</version> <!-- or the latest version -->
</dependency>

For Gradle:

implementation 'org.jfree:jfreechart:1.5.3'

Basic Usage

Creating a Simple Bar Chart

A bar chart is one of the most common chart types used to represent data.

Example

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.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

import javax.swing.*;

public class BarChartExample extends JFrame {

    public BarChartExample(String title) {
        super(title);

        // Create Dataset
        CategoryDataset dataset = createDataset();

        // Create chart
        JFreeChart chart = ChartFactory.createBarChart(
                "Bar Chart Example", // Chart title
                "Category", // X-Axis Label
                "Score", // Y-Axis Label
                dataset,
                PlotOrientation.VERTICAL,
                true, true, false);

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

    private CategoryDataset createDataset() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        dataset.addValue(80, "Math", "Ravi");
        dataset.addValue(70, "Math", "Sita");
        dataset.addValue(60, "Math", "Pooja");

        dataset.addValue(85, "Science", "Ravi");
        dataset.addValue(75, "Science", "Sita");
        dataset.addValue(90, "Science", "Pooja");

        return dataset;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            BarChartExample example = new BarChartExample("Bar Chart Example");
            example.setSize(800, 400);
            example.setLocationRelativeTo(null);
            example.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            example.setVisible(true);
        });
    }
}

Explanation: This example demonstrates how to create a simple bar chart using JFreeChart. The ChartFactory.createBarChart method is used to create the chart, and a DefaultCategoryDataset is used to provide the data.

Creating a Simple Pie Chart

A pie chart is used to represent data as slices of a pie.

Example

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

import javax.swing.*;

public class PieChartExample extends JFrame {

    public PieChartExample(String title) {
        super(title);

        // Create dataset
        PieDataset dataset = createDataset();

        // Create chart
        JFreeChart chart = ChartFactory.createPieChart(
                "Pie Chart Example", dataset, true, true, false);

        // Create Panel
        ChartPanel panel = new ChartPanel(chart);
        setContentPane(panel);
    }

    private PieDataset createDataset() {
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("Ravi", 50);
        dataset.setValue("Sita", 20);
        dataset.setValue("Pooja", 30);
        return dataset;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            PieChartExample example = new PieChartExample("Pie Chart Example");
            example.setSize(800, 400);
            example.setLocationRelativeTo(null);
            example.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            example.setVisible(true);
        });
    }
}

Explanation: This example demonstrates how to create a simple pie chart using JFreeChart. The ChartFactory.createPieChart method is used to create the chart, and a DefaultPieDataset is used to provide the data.

Creating a Simple Line Chart

A line chart is used to display information as a series of data points called 'markers' connected by straight line segments.

Example

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import javax.swing.*;

public class LineChartExample extends JFrame {

    public LineChartExample(String title) {
        super(title);

        // Create dataset
        XYDataset dataset = createDataset();

        // Create chart
        JFreeChart chart = ChartFactory.createXYLineChart(
                "Line Chart Example",
                "X-Axis",
                "Y-Axis",
                dataset);

        // Create Panel
        ChartPanel panel = new ChartPanel(chart);
        setContentPane(panel);
    }

    private XYDataset createDataset() {
        XYSeriesCollection dataset = new XYSeriesCollection();

        XYSeries series1 = new XYSeries("2016");
        series1.add(1, 500);
        series1.add(2, 694);
        series1.add(3, 820);
        dataset.addSeries(series1);

        XYSeries series2 = new XYSeries("2017");
        series2.add(1, 710);
        series2.add(2, 905);
        series2.add(3, 1020);
        dataset.addSeries(series2);

        return dataset;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            LineChartExample example = new LineChartExample("Line Chart Example");
            example.setSize(800, 400);
            example.setLocationRelativeTo(null);
            example.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            example.setVisible(true);
        });
    }
}

Explanation: This example demonstrates how to create a simple line chart using JFreeChart. The ChartFactory.createXYLineChart method is used to create the chart, and an XYSeriesCollection is used to provide the data.

Advanced Features

Customizing Charts

You can customize various aspects of the charts, such as the background color, plot color, and legend position.

Example

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import javax.swing.*;
import java.awt.*;

public class CustomChartExample extends JFrame {

    public CustomChartExample(String title) {
        super(title);

        // Create dataset
        XYDataset dataset = createDataset();

        // Create chart
        JFreeChart chart = ChartFactory.createXYLineChart(
                "Customized Line Chart Example",
                "X-Axis",
                "Y-Axis",
                dataset,
                PlotOrientation.VERTICAL,
                true, true, false);

        // Customize chart
        XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);

        chart.setTitle(new TextTitle("Customized Line Chart Example",
                new Font("Serif", java.awt.Font.BOLD, 18)
        ));

        // Create Panel
        ChartPanel panel = new ChartPanel(chart);
        setContentPane(panel);
    }

    private XYDataset createDataset() {
        XYSeriesCollection dataset = new XYSeriesCollection();

        XYSeries series1 = new XYSeries("2016");
        series1.add(1, 500);
        series1.add(2, 694);
        series1.add(3, 820);
        dataset.addSeries(series1);

        XYSeries series2 = new XYSeries("2017");
        series2.add(1, 710);
        series2.add(2, 905);
        series2.add(3, 1020);
        dataset.addSeries(series2);

        return dataset;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            CustomChartExample example = new CustomChartExample("Customized Line Chart Example");
            example.setSize(800, 400);
            example.setLocationRelativeTo(null);
            example.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            example.setVisible(true);
        });
    }
}

Explanation: This example demonstrates how to customize a chart. The background color, gridline color, and chart title are customized using various methods provided by the JFreeChart and XYPlot classes.

Creating Multiple Charts

You can create multiple charts and display them in a single frame.

Example

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.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;





import javax.swing.*;
import java.awt.*;

public class MultipleChartsExample extends JFrame {

    public MultipleChartsExample(String title) {
        super(title);

        setLayout(new GridLayout(2, 2));

        // Create datasets
        CategoryDataset barDataset = createBarDataset();
        PieDataset pieDataset = createPieDataset();

        // Create charts
        JFreeChart barChart = ChartFactory.createBarChart(
                "Bar Chart Example", "Category", "Score",
                barDataset, PlotOrientation.VERTICAL,
                true, true, false);

        JFreeChart pieChart = ChartFactory.createPieChart(
                "Pie Chart Example", pieDataset, true, true, false);

        // Add charts to frame
        add(new ChartPanel(barChart));
        add(new ChartPanel(pieChart));
    }

    private CategoryDataset createBarDataset() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.addValue(80, "Math", "Ravi");
        dataset.addValue(70, "Math", "Sita");
        dataset.addValue(60, "Math", "Pooja");

        dataset.addValue(85, "Science", "Ravi");
        dataset.addValue(75, "Science", "Sita");
        dataset.addValue(90, "Science", "Pooja");

        return dataset;
    }

    private PieDataset createPieDataset() {
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("Ravi", 50);
        dataset.setValue("Sita", 20);
        dataset.setValue("Pooja", 30);
        return dataset;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MultipleChartsExample example = new MultipleChartsExample("Multiple Charts Example");
            example.setSize(800, 600);
            example.setLocationRelativeTo(null);
            example.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            example.setVisible(true);
        });
    }
}

Explanation: This example demonstrates how to create multiple charts and display them in a single frame. A GridLayout is used to arrange the charts in a grid, and ChartPanel instances are added to the frame.

Exporting Charts to Image Files

You can export charts to image files such as PNG or JPEG.

Example

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.chart.ChartUtils;

import java.io.File;
import java.io.IOException;

public class ExportChartExample {

    public static void main(String[] args) {
        // Create dataset
        CategoryDataset dataset = createDataset();

        // Create chart
        JFreeChart chart = ChartFactory.createBarChart(
                "Bar Chart Example",
                "Category",
                "Score",
                dataset,
                PlotOrientation.VERTICAL,
                true, true, false);

        // Save chart as PNG
        try {
            ChartUtils.saveChartAsPNG(new File("BarChart.png"), chart, 800, 600);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static CategoryDataset createDataset() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.addValue(80, "Math", "Ravi");
        dataset.addValue(70, "Math", "Sita");
        dataset.addValue(60, "Math", "Pooja");

        dataset.addValue(85, "Science", "Ravi");
        dataset.addValue(75, "Science", "Sita");
        dataset.addValue(90, "Science", "Pooja");

        return dataset;
    }
}

Explanation: This example demonstrates how to export a chart to an image file. The ChartUtils.saveChartAsPNG method is used to save the chart as a PNG file.

Conclusion

JFreeChart is a versatile and powerful library for creating a wide range of charts in Java. This guide covered the basics of creating bar charts, pie charts, and line charts, as well as advanced features such as customizing charts, creating multiple charts, and exporting charts to image files. By leveraging JFreeChart, you can create visually appealing and interactive charts to visualize data in your Java applications. For more detailed information and advanced features, refer to the official JFreeChart documentation.

Comments