前言
JFreeChart是一个免费的Java开源绘图库,可以绘制折线图、条形图、饼图等,同时支持多种输出格式,包括PNG,JPEG,PDF和SVG
jfreechart github 地址
导入依赖
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.5.4</version>
</dependency>
折线图
public class LineChartDemo {
public static void main(String[] args) {
XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries series1 = new XYSeries("Line 1");
series1.add(1,4);
series1.add(3,7);
series1.add(5,5);
dataset.addSeries(series1);
XYSeries series2 = new XYSeries("Line 2");
series2.add(1,7);
series2.add(3,4);
series2.add(5,6);
dataset.addSeries(series2);
JFreeChart xyLineChart = ChartFactory.createXYLineChart("XY Line Chart", "X",
"Y", dataset);
ChartFrame frame = new ChartFrame("Demo", xyLineChart);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(300, 100);//窗口位置
frame.setSize(800, 400);//窗口大小
frame.setVisible(true);
}
}
柱状图
public class BarChartDemo {
public static void main(String[] args) {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(7445, "A", "I");
dataset.addValue(24448, "B", "I");
dataset.addValue(4297, "A", "II");
dataset.addValue(21022, "B", "II");
JFreeChart barChart = ChartFactory.createBarChart("Bar Chart", "category",
"value", dataset);
ChartFrame frame = new ChartFrame("Demo", barChart);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(300, 100);//窗口位置
frame.setSize(800, 400);//窗口大小
frame.setVisible(true);
}
}
饼图
public class PieChartDemo {
public static void main(String[] args) {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("Samsung", 27.8d);
dataset.setValue("Others", 55.3d);
dataset.setValue("Nokia", 16.8d);
dataset.setValue("Apple", 17.1d);
JFreeChart barChart = ChartFactory.createPieChart("Pie Chart", dataset);
ChartFrame frame = new ChartFrame("Demo", barChart);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(300, 100);//窗口位置
frame.setSize(800, 400);//窗口大小
frame.setVisible(true);
}
}