1. Overview
1.概述
In this tutorial, we’ll see how to use JFreeChart, a comprehensive Java library for creating a wide variety of charts. We can use it to integrate graphical data representations into a Swing application. It also includes a separate extension for JavaFX.
在本教程中,我们将了解如何使用 JFreeChart,这是一个用于创建各种图表的综合性 Java 库。我们可以使用它将图形数据表示集成到 Swing 应用程序中。它还包括用于 JavaFX 的 独立扩展。
We’ll start with the basics, covering setup and chart creation, and try a few different types of charts.
我们将从基础开始,包括设置和创建图表,并尝试几种不同类型的图表。
2. Creating Our First Chart
2.绘制第一张图表
JFreeChart allows us to create line charts, bar charts, pie charts, scatter plots, time series charts, histograms, and others. It can also combine different charts into a single view.
JFreeChart 允许我们创建折线图、条形图、饼图、散点图、时间序列图、直方图等。它还可以将不同的图表合并到一个视图中。
2.1. Setting Up Dependencies
2.1.设置依赖关系
To get started, we need to add the jfreechart artifact to our pom.xml file:
要开始使用,我们需要将 jfreechart 工具添加到 pom.xml 文件中:
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.5.4</version>
</dependency>
We should always check the latest release and its JDK compatibility to make sure our project is up-to-date and working properly. In this case, version 1.5.4 requires JDK8 or later.
我们应始终检查最新版本及其 JDK 兼容性,以确保我们的项目是最新的并能正常运行。在这种情况下,1.5.4 版本需要 JDK8 或更高版本。
2.2. Creating a Basic Line Chart
2.2.创建基本折线图
Let’s start by using DefaultCategoryDataset to create a dataset for our graph:
首先,让我们使用 DefaultCategoryDataset 为我们的图表创建一个数据集:
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(200, "Sales", "January");
dataset.addValue(150, "Sales", "February");
dataset.addValue(180, "Sales", "March");
dataset.addValue(260, "Sales", "April");
dataset.addValue(300, "Sales", "May");
Now, we can create a JFreeChart object that uses the previous dataset to plot a line chart.
现在,我们可以创建一个 JFreeChart 对象,使用之前的数据集绘制折线图。
The ChartFactory.createLineChart method takes the chart title, the x-axis and y-axis labels, and the dataset as parameters:
ChartFactory.createLineChart 方法将图表标题、X 轴和 Y 轴标签以及数据集作为参数:
JFreeChart chart = ChartFactory.createLineChart(
"Monthly Sales",
"Month",
"Sales",
dataset);
Next, a ChartPanel object is essential for displaying our chart within a Swing component. This object is then used as a JFrame content pane to create the application window:
接下来,一个 ChartPanel 对象对于在 Swing 组件中显示我们的图表至关重要。然后,该对象将用作 JFrame 内容窗格,以创建应用程序窗口:
ChartPanel chartPanel = new ChartPanel(chart);
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setContentPane(chartPanel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
When we run this code, we’ll see our Monthly Sales graph:
运行此代码后,我们将看到月销售额图表:
As we can see, we’ve created a chart using only a small amount of code.
正如我们所看到的,我们只用了少量代码就创建了一个图表。
3. Exploring Different Types of Charts
3.探索不同类型的图表
In the remaining examples, we’ll try some different types of charts. We won’t need to change the code much.
在剩下的示例中,我们将尝试一些不同类型的图表。我们不需要对代码做太大改动。
3.1. Bar Charts
3.1.条形图
We can modify the JFreeChart creation code to convert our line graph to a bar chart:
我们可以修改 JFreeChart 创建代码,将折线图转换为条形图:
JFreeChart chart = ChartFactory.createBarChart(
"Monthly Sales",
"Month",
"Sales",
dataset);
This plots the dataset from the previous example:
绘制上一示例中的数据集:
As we can see, JFreeChart is quite flexible, making it easy to display the same data with different kinds of charts.
正如我们所见,JFreeChart 非常灵活,可以轻松地用不同类型的图表显示相同的数据。
3.2. Pie Charts
3.2.饼图
Pie charts show the proportion of parts within a whole. To create a pie chart, we need to use the DefaultPieDataset class to create our dataset. We also use the createPieChart() method to build our JFreeChart object:
饼图显示整体中各部分的比例。要创建饼图,我们需要使用 DefaultPieDataset 类来创建我们的数据集。我们还将使用 createPieChart() 方法来构建我们的 JFreeChart 对象:
DefaultPieDataset<String> dataset = new DefaultPieDataset<>();
dataset.setValue("January", 200);
dataset.setValue("February", 150);
dataset.setValue("March", 180);
JFreeChart chart = ChartFactory.createPieChart(
"Monthly Sales",
dataset,
true, // include legend
true, // generate tooltips
false); // no URLs
Tooltips showing absolute sales in a month and relative percentage of the total are visible when we hover the mouse over a slice of the pie:
当鼠标悬停在饼的某个部分上时,就会出现工具提示,显示一个月的绝对销售额和占总销售额的相对百分比:
Finally, we should note that there are several variations of the ChartFactory.createPieChart() method for finer customization.
最后,我们需要注意的是,ChartFactory.createPieChart()方法有多种变体,可用于更精细的自定义。
3.3. Time Series Charts
3.3.时间序列图
Time series charts show trends in data over time. To construct the dataset, we need a TimeSeriesCollection object, which is a collection of TimeSeries objects, each of which is a sequence of data items containing a value related to a specific time period:
时间序列图显示数据随时间变化的趋势。要构建数据集,我们需要一个 TimeSeriesCollection 对象,它是 TimeSeries 对象的集合,其中每个对象都是包含与特定时间段相关的值的数据项序列:
TimeSeries series = new TimeSeries("Monthly Sales");
series.add(new Month(1, 2024), 200);
series.add(new Month(2, 2024), 150);
series.add(new Month(3, 2024), 180);
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(series);
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Monthly Sales",
"Date",
"Sales",
dataset,
true, // legend
false, // tooltips
false); // no URLs
Let’s see the result:
让我们看看结果吧:
This example shows the power of JFreeChart in plotting time series data, making it easy to track changes over time.
该示例展示了 JFreeChart 在绘制时间序列数据方面的强大功能,可轻松跟踪随时间发生的变化。
3.4. Combination Charts
3.4.组合图
Combination charts allow us to combine different types of charts into one. Compared to the previous examples, the code is a bit more complex.
组合图表允许我们将不同类型的图表组合成一个。与前面的示例相比,代码要复杂一些。
We need to use DefaultCategoryDataset to store the data, but here, we create two instances, one for each chart type:
我们需要使用 DefaultCategoryDataset 来存储数据,但在这里,我们创建了两个实例,每个图表类型一个:
DefaultCategoryDataset lineDataset = new DefaultCategoryDataset();
lineDataset.addValue(200, "Sales", "January");
lineDataset.addValue(150, "Sales", "February");
lineDataset.addValue(180, "Sales", "March");
DefaultCategoryDataset barDataset = new DefaultCategoryDataset();
barDataset.addValue(400, "Profit", "January");
barDataset.addValue(300, "Profit", "February");
barDataset.addValue(250, "Profit", "March");
CategoryPlot creates the plot area that contains both types of charts. It allows us to assign datasets to renderers — LineAndShapeRenderer for lines, and BarRenderer for bars:
CategoryPlot 创建了包含两种类型图表的绘图区域。它允许我们将数据集分配给呈现器 – LineAndShapeRenderer 用于线条,BarRenderer 用于条形图:
CategoryPlot plot = new CategoryPlot();
plot.setDataset(0, lineDataset);
plot.setRenderer(0, new LineAndShapeRenderer());
plot.setDataset(1, barDataset);
plot.setRenderer(1, new BarRenderer());
plot.setDomainAxis(new CategoryAxis("Month"));
plot.setRangeAxis(new NumberAxis("Value"));
plot.setOrientation(PlotOrientation.VERTICAL);
plot.setRangeGridlinesVisible(true);
plot.setDomainGridlinesVisible(true);
Finally, let’s use JFreeChart to create the final chart:
最后,让我们使用 JFreeChart 创建最终图表:
JFreeChart chart = new JFreeChart(
"Monthly Sales and Profit",
null, // null means to use default font
plot, // combination chart as CategoryPlot
true); // legend
This setup allows for a combined presentation of data that visually demonstrates the synergy between sales and profit:
通过这种设置,可以综合展示数据,直观地显示销售额和利润之间的协同作用:
This way, JFreeChart can present complex datasets that require multiple chart types for better understanding and analysis.
这样,JFreeChart 就可以呈现需要多种图表类型的复杂数据集,以便更好地理解和分析。
4. Conclusion
4.结论
In this article, we’ve explored the creation of different types of charts with JFreeChart, including line charts, bar charts, pie charts, time series charts, and combination charts.
在本文中,我们探讨了如何使用 JFreeChart 创建不同类型的图表,包括折线图、条形图、饼图、时间序列图和组合图。
This introduction only scratches the surface of what JFreeChart can do.
以上介绍只是 JFreeChart 功能的皮毛。
As always, the code for this article is available over on GitHub.
与往常一样,本文的代码可在 GitHub 上获取。