JFreeChart 之二:饼状图实现
JFreeChart 之一:柱状图实现
准备工作与相关环境参考JFreeChart之一
以下介绍饼状图的实现:
Action:
/* Action: */
// 从数据库中查询 需要显示的数据
List list = commonService.findBySql(query);
DefaultPieDataset dset = new DefaultPieDataset();
if(lt!=null && lt.size()>0){
int l=lt.size();
for(int j=0;j<l;j++){
Object[] o = (Object[]) lt.get(j);
dset.setValue(o[0].toString(), new Double(o[1].toString()));
}
PieDataset dataset = dset;
JFreeChart chart2 = ChartFactory.createPieChart3D("各区域人员录入统计", dataset, true, true, false);
JFreeChartUtil.piePlot3DStyle(chart2);
// 设置图标题的字体
Font font = new Font("宋体", Font.CENTER_BASELINE, 20);
TextTitle title = new TextTitle("各区域人员录入统计");
title.setFont(font);
chart2.setTitle(title);
chart2.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));
String filename2 = ServletUtilities.saveChartAsPNG(chart2, 800, 400,null, request.getSession());
String pieUrl2 = request.getContextPath()+ "/servlet/DisplayChart?filename=" + filename2;
request.setAttribute("chartUrl2", pieUrl2);
JFreeChartUtil.piePlot3DStyle
/* 饼图样式 */
public static void piePlot3DStyle(JFreeChart chart) {
PiePlot3D plot = (PiePlot3D) chart.getPlot();
plot.setLabelFont(new Font("宋体", 0, 12));
// 图片中显示百分比:默认方式
//plot.setLabelGenerator(new StandardPieSectionLabelGenerator(StandardPieToolTipGenerator.DEFAULT_TOOLTIP_FORMAT));
// 图片中显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位
plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
"{0}={1}({2})", NumberFormat.getNumberInstance(),
new DecimalFormat("0.00%")));
// 图例显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例
plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator(
"{0}={1}({2})"));
// 设置背景色为白色
chart.setBackgroundPaint(Color.white);
// 指定图片的透明度(0.0-1.0)
// plot.setForegroundAlpha(1.0f);
//设置透明度,0.5F为半透明,1为不透明,0为全透明
plot.setForegroundAlpha(0.5F);
// 指定显示的饼图上圆形(false)还椭圆形(true)
plot.setCircular(true);
//设置开始角度
plot.setStartAngle(40D);
//设置方向为”顺时针方向“
plot.setDirection(Rotation.CLOCKWISE);
plot.setInteriorGap(0.0D);//[7]
//没有数据的时候显示的内容
plot.setNoDataMessage("无数据显示");
plot.setNoDataMessageFont(new Font("宋体", 0, 12));
plot.setLabelGap(0.02D);
// 设置饼图背景色
plot.setBackgroundPaint(Color.white);
}
jsp
<img src="${chartUrl2}" mce_src="${chartUrl2}" />
效果: