JFreeChart是Java平台上的一个开放的图标绘制类库,它完全使用Java语言编写。JFreeChart可生成饼图、柱状图、散点图、时序图、甘特图等,并且可以产生PNG和JPEG格式的输出,还可以与PDF和EXCEL关联。
JFreeChart下载地址:http://www.jfree.org/jfreechart/download.html
下载完成后,将下面两个jar包加入classpath即可(xx为下载的版本):
jcommon-xx.jar
jfreechart-xx.jar
在本实验中,只需利用jfreechart生成柱状图,因此在这里只讨论柱状图的生成方法。
创建BarChart:
public void creatBarChart(String filePath, DefaultCategoryDataset dataset) {
try{
setChartTheme();
JFreeChart chart = ChartFactory.creatBarChart3D("不同最大速度下吞吐率和公平性差异","不同最大速度","",dateset,PlotOrientation.VERTICAL,true,true,false);
ChartUtilities.saveChartAsJPEG(new File(filePath),chart,800,300);
}catch(IOException e){
e.printStackTrace();
}
}
设置chartFactory的主题,可解决乱码问题:
private void setChartTheme() {
// 创建主题样式
StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
// 设置标题字体
standardChartTheme.setExtraLargeFont(new Font("宋书", Font.BOLD, 20));
// 设置图例的字体
standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));
// 设置轴向的字体
standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));
// 应用主题样式
ChartFactory.setChartTheme(standardChartTheme);
}
获得复杂BarChart的数据集:
public DefaultCategoryDataset getBarDataSet1(int i) {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
if (i == 1) {
dataset.addValue(1.754, "吞吐率", "MV=5");
dataset.addValue(0.754, "公平性", "MV=5");
dataset.addValue(1.667, "吞吐率", "MV=8");
dataset.addValue(0.744, "公平性", "MV=8");
dataset.addValue(1.754, "吞吐率", "MV=10");
dataset.addValue(0.815, "公平性", "MV=10");
//dataset.addValue(0.588, "吞吐率", "t=4");
//dataset.addValue(0.853, "公平性", "t=4");
//dataset.addValue(0.472, "吞吐率", "t=5");
//dataset.addValue(0.928, "公平性", "t=5");
} else {
dataset.addValue(594, "Strategy1", "file1-O");
dataset.addValue(1058, "Strategy2", "file1-O");
dataset.addValue(1637, "Strategy3", "file1-O");
dataset.addValue(937, "Strategy1", "file2-O");
dataset.addValue(1689, "Strategy2", "file2-O");
dataset.addValue(1837, "Strategy3", "file2-O");
dataset.addValue(959, "Strategy1", "file3-O");
dataset.addValue(884, "Strategy2", "file3-O");
dataset.addValue(1772, "Strategy3", "file3-O");
dataset.addValue(723, "Strategy1", "file4-O");
dataset.addValue(1646, "Strategy2", "file4-O");
dataset.addValue(1821, "Strategy3", "file4-O");
}
return dataset;
}
factory:
public static void factory(String filePath, DefaultCategoryDataset dataset) {
BarChart piechart = new BarChart();
piechart.createBarChart(filePath, dataset);
System.out.println("PieChart file path : " + filePath);
try {
Runtime.getRuntime().exec("rundll32 url.dll FileProtocolHandler " + filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
main函数:
public static void main(String[] args) {
BarChart.factory("src/gui/CompareDifferentMV.jpg",
new BarChart().getBarDataSet1(1));
}
一个生成的图片示例如下:
每次生成不同的柱状图时,只需要修改图的主题和具体数据即可。