/**
* 生成饼图
* @param keys section的名称
* @param values section的值
* @param title 饼图的标题
* @param session
* @return 生成的饼图的文件名
*/
public String createPieChart(List keys, List values ,String title, HttpSession session){
DefaultPieDataset data = new DefaultPieDataset();
if(keys!=null && keys.size()>0 && values!=null && values.size()>0)
for(int i=0;i<keys.size();i++){
Comparable key = (Comparable)keys.get(i);
Number value = (Number)values.get(i);
data.setValue(key, value);
}
PiePlot3D pieplot3d = new PiePlot3D(data);
JFreeChart chart = new JFreeChart("",JFreeChart.DEFAULT_TITLE_FONT, pieplot3d, true);
//设置开始角度
pieplot3d.setStartAngle(150D);
//设置方向为”顺时针方向“
pieplot3d.setDirection(Rotation.CLOCKWISE);
//设置透明度,0.5F为半透明,1为不透明,0为全透明
pieplot3d.setForegroundAlpha(0.5F);
pieplot3d.setNoDataMessage("无数据显示");// 没有数据的时候显示的内容
//pieplot3d.setExplodePercent(arg0, arg1);
pieplot3d.setLabelGenerator(new StandardPieSectionLabelGenerator(
("{0}: ({2})"), NumberFormat.getNumberInstance(),
new DecimalFormat("0.00%")));
chart.setBackgroundPaint(java.awt.Color.white);//可选,设置图片背景色
chart.setTitle(title);//可选,设置图片标题
ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
String filename="";
try {
//500是图片长度,300是图片高度
filename = ServletUtilities.saveChartAsPNG(chart, 500, 300, info, session);
//graphURL = request.getContextPath() + "/DisplayChart?filename=" + filename;
} catch (IOException e) {
e.printStackTrace();
}
return filename;
}
其中new StandardPieSectionLabelGenerator(
("{0}: ({1},{2})"), NumberFormat.getNumberInstance(),
new DecimalFormat("0.00%"))
的("{0}: ({1},{2})")是生成的格式,{0}表示section名,{1}表示section的值,{2}表示百分比。可以自定义。而new DecimalFormat("0.00%")表示小数点后保留两位。
在jsp页面中引用的方法:
<%
String filename=tem.createPieChart(keys,values,"统计图",session);
String graphURL = request.getContextPath() + "/DisplayChart?filename=" + filename;
%>
<img src="<%= graphURL %>" width=500 height=300 border=0 >