JFreeChart饼图



 最近开发时,要对一些东西进行统计时用到了JFreeChart画图,所以稍微研究了一下JFreeChart,下面是画饼图的方法的部分代码:

 

	/**
	 * 饼图
	 */
	private JFreeChart getPieChart() {
		String sql = "select count(id) num,modulename mname from tongji group by mname";
		List list = getList(sql);
		
		//创建DefaultPieDataset数据集
		DefaultPieDataset dpd = new DefaultPieDataset();
		for (Object obj : list) {
			Map<String, Object> map = (Map<String, Object>) obj;
			//添加数据
			dpd.setValue((String) map.get("mname"), (Number) map.get("num"));
		}
		
		//创建绘制3D效果饼形图的JFreeChart实例
		JFreeChart chart = ChartFactory.createPieChart3D("图片标题",// 图片标题
				dpd, // 绘图数据集
				true, // 设定是否显示图例
				false, // 设定是否显示图例名称
				false); // 设定是否生成链接
		
		//当需要在图片上显示中文时,建议不要使用反锯齿功能,这样能够保证汉字的清晰度
		chart.setAntiAlias(true);//是否启用反锯齿功能
		chart.setBackgroundPaint(Color.LIGHT_GRAY);//设置背景色

		//可以自行定义图表标题的字体、样式、大小和颜色等
		TextTitle title = chart.getTitle();
		title.setFont(new Font("黑体", Font.BOLD, 20)); //标题字体
		title.setPaint(Color.BLACK);//标题字体颜色
		title.setBackgroundPaint(Color.WHITE);//标题背景
		
		LegendTitle legend = chart.getLegend();//得到图例对象
		legend.setBackgroundPaint(Color.WHITE);//图例背景
		legend.setItemFont(new Font("宋体", Font.ITALIC, 12)); // 图例的字体
		legend.setPosition(RectangleEdge.BOTTOM);//图例位置
		
		//通过绘图区对象设置饼状图的效果
		PiePlot plot = (PiePlot) chart.getPlot();//得到绘图区对象
		
		plot.setLabelFont(new Font("宋体", Font.ITALIC, 12)); // 图片上的文字的字体
		plot.setOutlineStroke(new BasicStroke(1));//边框粗细
		plot.setOutlinePaint(Color.GRAY);//边框颜色
		
		plot.setCircular(false);//默认为圆形,建议在绘制3D效果图时将其设为False
		plot.setStartAngle(90);// 设置第一部分 的开始位置
		plot.setDirection(Rotation.ANTICLOCKWISE);//设置绘制方向为逆时针
		plot.setForegroundAlpha(0.65f);// 指定图片的透明度
		
		String unitSytle = "{0}={1}({2})"; //样式: A部分=35(15.98%)
		plot.setLabelGenerator(new StandardPieSectionLabelGenerator(unitSytle,
				NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));// 引出标签显示样式
		plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator(
				unitSytle, NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));// 图例显示样式

		//没有数据时显示的内容
		plot.setNoDataMessage("无对应的数据,请重新查询。");
		plot.setNoDataMessagePaint(Color.red);
		plot.setNoDataMessageFont(new Font("黑体", Font.BOLD, 20));
		
		return chart;
	}

 

有了JFreeChart对象,剩下的工作就非常简单了,如果只是显示一下可以:

JFreeChart chart = getPieChart();
ChartFrame pieFrame = new ChartFrame("统计图", chart);
pieFrame.pack();
pieFrame.setVisible(true);

 

还可以生成一张本地图片,保存在磁盘上:

        try {
          File file = new File("D:/tj.png"); //保存的位置
          ChartUtilities.saveChartAsPNG(file,chart,800,500);//保存为长为:800,高为500
  } catch (IOException e) {
   e.printStackTrace();
  }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值