jfreechart 柱状图上面的数字显示



jfreechart 柱状图上面的数字显示。最近在做柱状图时, 每个柱状图上面要显示具体的数据(主要是数字), 特写了一下例子,可以解决此问题.

得到数据对象
private static CategoryDataset getDataSet() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(100, “”, “苹果”);
dataset.addValue(200, “”, “梨子”);
dataset.addValue(300, “”, “葡萄”);
dataset.addValue(400, “”, “香蕉”);
dataset.addValue(500, “”, “荔枝”);
return dataset;
}
设置编码
public static void setStandardChartTheme() {
//创建主题样式
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);
}
设置jfreechart对象和 图形显示数据设置
JFreeChart chart = ChartFactory.createBarChart3D(“水果产量图”, // 图表标题
“水果”, // 目录轴的显示标签(x轴)
“产量”, // 数值轴的显示标签(y轴)
dataset, // 数据集
PlotOrientation.VERTICAL, // 图表方向:水平、垂直
false, // 是否显示图例(对于简单的柱状图必须是false)
false, // 是否生成工具
false // 是否生成URL链接
);

CategoryPlot plot = (CategoryPlot) chart.getCategoryPlot();
BarRenderer renderer = (BarRenderer) plot.getRenderer();
// 显示条目标签
renderer.setBaseItemLabelsVisible(true);
// 设置条目标签生成器,在JFreeChart1.0.6之前可以通过renderer.setItemLabelGenerator(CategoryItemLabelGenerator
// generator)方法实现,但是从版本1.0.6开始有下面方法代替
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
// 设置条目标签显示的位置,outline表示在条目区域外,baseline_center表示基于基线且居中
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));

最后输出到jsp页面
OutputStream os = resp.getOutputStream();
ChartUtilities.writeChartAsJPEG(os, 1.0f, chart, 400, 300, null);
os.close();