JFreechar工具类(自己的)

这是一个使用 JFreeChart 库生成各种图形的 Java 工具类,包括环形图、折线图、柱状图和饼图。工具提供了自定义图形尺寸、颜色、标签、图例位置等功能,并能保存为 PNG 图片。例如,createAnnularChar 方法用于生成环形图,createWireChar 用于生成折线图,createPillarChart 用于生成柱状图,createPieChart 用于生成饼图。
import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.RingPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.ui.RectangleEdge;

import com.growatt.oss.system.StaticParamUtils;

import aj.org.objectweb.asm.Type;

/**
 * 生成图工具
 * @author Administrator
 *
 */
public class JFreeChartUtils {
	
	
	/**
	 * 环形图
	 * @param charName 副标题
	 * @param charCount 总数
	 * @param dataset 数据集
	 * @param chartTitle 图标题
	 * @param pieKeys 环形图的名字集
	 * @param width 宽度
	 * @param height 高度
	 * @return
	 */
	public static  String createAnnularChar(PieDataset dataset,
	        String chartTitle, String[] pieKeys, String charName,int width,int height){
		
		JFreeChart chart = ChartFactory.createRingChart(chartTitle,dataset,true,true, false);
		chart.setBorderVisible(false);
		chart.setTextAntiAlias(false);		// 使下说明标签字体清晰,去锯齿类似于
		chart.setBackgroundPaint(Color.white);		// 图片背景色
		
		RingPlot ringplot=(RingPlot) chart.getPlot();
		ringplot.setOutlineVisible(false);            	  //坐标区表框是否显示
		ringplot.setBackgroundAlpha(0.8f);
		//ringplot.setNoDataMessage("无对应的数据,请重新查询。");		// 设置无数据时的信息
		ringplot.setNoDataMessagePaint(Color.red);  			// 设置无数据时的信息显示颜色
		ringplot.setLabelFont(new Font("宋体", Font.BOLD, 15));
		// 设置饼状图和环形图的显示数字。0代表显示文字说明,1代表显示数字,2代表显示数字以百分比的方式如果多个结合{0}:{1}
        ringplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{2}"));
        ringplot.setBackgroundPaint(Color.white);//设置背景色
        
        ringplot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({1})", NumberFormat.getNumberInstance(),
    			new DecimalFormat("0.00%"))); //设置图例数据格式
        ChartFrame mChartFrame = new ChartFrame("环形图", chart);
        mChartFrame.pack();
        
        LegendTitle legendTitle = chart.getLegend();//获得图例标题
	   	legendTitle.setPosition(RectangleEdge.RIGHT);//图例右边显示
	   	legendTitle.setBorder(0, 0, 0, 0);//设置图例上下左右线
	   	legendTitle.setPadding(0, 0, 0, 50);
	   	
	   	// 设置图标题的字体重新设置title
	 	Font font = new Font("隶书", Font.BOLD, 25);
	 	TextTitle title = new TextTitle(chartTitle);
	 	title.setFont(font);
	 	chart.setTitle(title);
	 	
	 	if (charName != null) {
	 		Font font2 = new Font("宋体", Font.BOLD, 15);
		 	TextTitle title2 = new TextTitle(charName);
		 	title2.setFont(font2);
		 	chart.addSubtitle(title2);
		}
	 	
		FileOutputStream fos_jpg = null;
		try{
			String name = System.currentTimeMillis()+""+Math.round((Math.random()+1) * 1000)+".png";
			// 文件夹不存在则创建
			String chartName = StaticParamUtils.COMMONFILEPATH + name;
			fos_jpg = new FileOutputStream(chartName);
			// 高宽的设置
			ChartUtilities.writeChartAsPNG(fos_jpg, chart, width, height);
			return chartName;
		}
		catch (Exception e){
			e.printStackTrace();
			return null;
		}
		finally{
			try{
				fos_jpg.close();
			}
			catch (Exception e){
				e.printStackTrace();
			}
		}

	}
	
	
	/**
	 * 折线图
     * @param x x轴的说明(如种类,时间等)
     * @param y y轴的说明(如速度,时间等)
	 * @param dataset 数据集
	 * @param chartTitle 图标题
	 * @param pieKeys 环形图的名字集
	 * @param width 宽度
	 * @param height 高度
	 * @param num y轴0.平放  1.倾斜45度  2.倾斜90度
	 * @param type num为不在线上显示数据
	 * @return
	 */
	public static String createWireChar(int num,String type,String chartTitle, String x, String y,
	        CategoryDataset dataset,int width,int height){

		JFreeChart chart = ChartFactory.createLineChart(chartTitle, x, y,
				dataset, PlotOrientation.VERTICAL, false, true, false);
		chart.setTextAntiAlias(false);
		chart.setBackgroundPaint(Color.WHITE);
		chart.setBorderVisible(false);                             //设置边框是否可见
		CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
		categoryplot.setOutlinePaint(Color.WHITE); 
		
		ValueAxis valueAxis = categoryplot.getRangeAxis();
		valueAxis.setAutoRange(true);		//自动设置坐标值的间距
		valueAxis.setAxisLineVisible(false);
		LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer();
		lineandshaperenderer.setSeriesPaint(0,Color.blue);   //设置每个分组的线的颜色
		if (type!=null) {
//			valueAxis.setVisible(false);		是否显示y轴
			// 获得renderer 注意这里是下嗍造型到lineandshaperenderer!!
			lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见
			lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见
			lineandshaperenderer.setBaseItemLabelsVisible(true);
			lineandshaperenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}%",NumberFormat.getNumberInstance()));
			// 设置线条是否被显示填充颜色
			lineandshaperenderer.setUseFillPaint(true);
			lineandshaperenderer.setBaseFillPaint(Color.blue);//蓝色
		}
		
		// 设置面板字体
		Font labelFont = new Font("宋体",Font.BOLD, 12);
		CategoryAxis domainAxis = categoryplot.getDomainAxis();
		domainAxis.setLabelFont(labelFont);// 轴标题
		domainAxis.setTickLabelFont(labelFont);// 轴数值
		if (num == 0) {
        	domainAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);
		}else if (num == 1) {
			domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
		}else{
			domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
		}
		NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
		numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
		numberaxis.setAutoRangeIncludesZero(true);
//	    numberaxis.setTickUnit(new NumberTickUnit(number));		//设置纵坐标值的间距为2
		// 设置图标题的字体重新设置title
		Font font = new Font("隶书", Font.BOLD, 25);
		TextTitle title = new TextTitle(chartTitle);
		title.setFont(font);
		chart.setTitle(title);

		FileOutputStream fos_jpg = null;
		try{
			String name = System.currentTimeMillis()+""+Math.round((Math.random()+1) * 1000)+".png";
			String chartName = StaticParamUtils.COMMONFILEPATH + name;
			fos_jpg = new FileOutputStream(chartName);

			// 将报表保存为png文件
			ChartUtilities.writeChartAsPNG(fos_jpg, chart,width, height );

			return chartName;
		}
		catch (Exception e){
			e.printStackTrace();
			return null;
		}
		finally{
			try{
				fos_jpg.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}
	
	/**
     * 柱状图
     * @param num 0 平放显示,1 45度显示,2 90显示
     * @param type  是否显示柱子上的值 为null表示不显示
     * @param width 宽度
	 * @param height 高度
     * @param dataset 数据集
     * @param x x轴的说明(如种类,时间等)
     * @param y y轴的说明(如速度,时间等)
     * @param chartTitle 图标题
     * @param charName 生成图片的名字
     * @return
     */
    public static String createPillarChart(int num,String type,CategoryDataset dataset, String x,String y,
    		String chartTitle,int width,int height){
        JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 图表标题
                x, 
                y, 
                dataset, 
                PlotOrientation.VERTICAL, 
                false, 
                false, 
                false 
                );
        Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);
        
        chart.setTextAntiAlias(false);
        chart.setBackgroundPaint(Color.white);
        CategoryPlot plot = chart.getCategoryPlot();
        plot.setRangeGridlinesVisible(true);// 设置横虚线可见
        plot.setRangeGridlinePaint(Color.gray);// 虚线色彩
        plot.setOutlinePaint(Color.WHITE); 	//边框颜色

        // 数据轴精度
        NumberAxis vn = (NumberAxis) plot.getRangeAxis();
        vn.setTickUnit(new NumberTickUnit(20));
        DecimalFormat df = new DecimalFormat("#0.00");
        vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式
        
        // x轴设置
        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setLabelFont(labelFont);// 轴标题
        domainAxis.setTickLabelFont(labelFont);// 轴数值
        if (num == 0) {
        	domainAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);
		}else if (num == 1) {
			domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
		}else{
			domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
		}
        
        domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 横轴上的 Lable 是否完整显示
        domainAxis.setLowerMargin(0.1);// 设置距离图片左端距离
        domainAxis.setUpperMargin(0.1);// 设置距离图片右端距离
        plot.setDomainAxis(domainAxis);
        plot.setBackgroundPaint(new Color(255, 255, 255)); // 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确)
        
        BarRenderer renderer = new BarRenderer();
        renderer.setSeriesPaint(0, new Color(100 ,149 ,237));//计划柱子的颜色
        renderer.setMaximumBarWidth(0.03);	// 设置柱子宽度
        renderer.setMinimumBarLength(0.2);	// 设置柱子高度
        renderer.setDrawBarOutline(false);	// 设置柱子边框可见
        
        ValueAxis rangeAxis = plot.getRangeAxis();// y轴设置
        rangeAxis.setLabelFont(labelFont);
        rangeAxis.setTickLabelFont(labelFont);
        rangeAxis.setUpperMargin(0.15); // 设置最高的一个 Item 与图片顶端的距离
        rangeAxis.setLowerMargin(0.15); // 设置最低的一个 Item 与图片底端的距离
        rangeAxis.setAxisLineVisible(false);	//y轴线是否显示
        rangeAxis.setAutoRange(true);                         //是否自动设置数据轴数据范围

        if (type != null) {
        	// 显示每个柱的数值,并修改该数值的字体属性
        	rangeAxis.setVisible(false);                           //Y轴内容是否显示
            renderer.setIncludeBaseInRange(true);
            renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
            renderer.setBaseItemLabelsVisible(true);
            renderer.setAutoPopulateSeriesFillPaint(true);//自动填充柱状体颜色
            renderer.setItemMargin(0.3);
		}
        plot.setRangeAxis(rangeAxis);
        plot.setRenderer(renderer);
        plot.setForegroundAlpha(1.0f);// 设置柱的透明度

        FileOutputStream fos_jpg = null;
        try{
        	String name = System.currentTimeMillis()+""+Math.round((Math.random()+1) * 1000)+".png";
            String chartName = StaticParamUtils.COMMONFILEPATH + name;
            fos_jpg = new FileOutputStream(chartName);
            ChartUtilities.writeChartAsPNG(fos_jpg, chart, width, height, true, 10);
            return chartName;
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }
        finally{
            try{
                fos_jpg.close();
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 饼图
     * @param dataset		数据集
     * @param chartTitle	标题
     * @param width			图形宽度
     * @param height		图形高度
     * @return
     */
    public static String createPieChart(PieDataset dataset,String chartTitle,int width,int height){
    	JFreeChart chart = ChartFactory.createPieChart(chartTitle, // chart
		        // title
		        dataset,// data
		        true,// include legend
		        true, false);
    	chart.setBackgroundPaint(Color.WHITE);		//设置外边颜色
    	
		PiePlot plot = (PiePlot) chart.getPlot();

		// 设置无数据时的信息
		plot.setNoDataMessage("无对应的数据,请重新查询。");
		// 设置无数据时的信息显示颜色
		plot.setNoDataMessagePaint(Color.red);
		// 图例显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例
		plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}"));
		plot.setLabelGenerator(null);		//去掉图形标签
		
		plot.setOutlinePaint(Color.WHITE);	 // 设置绘图面板外边的填充颜色
		plot.setShadowPaint(Color.WHITE); // 设置绘图面板阴影的填充颜色
		LegendTitle legend = chart.getLegend();		//图例边框颜色
		legend.setFrame(new BlockBorder(Color.WHITE));	//图例边框颜色
		
		FileOutputStream fos_jpg = null;
		try
		{
			// 文件夹不存在则创建
			String name = System.currentTimeMillis()+""+Math.round((Math.random()+1) * 1000)+".png";
            String chartName = StaticParamUtils.COMMONFILEPATH + name;
			fos_jpg = new FileOutputStream(chartName);
			// 高宽的设置影响椭圆饼图的形状
			ChartUtilities.writeChartAsPNG(fos_jpg, chart,width, height);
			return chartName;
		}
		catch (Exception e){
			e.printStackTrace();
			return null;
		}
		finally{
			try{
				fos_jpg.close();
			}
			catch (Exception e){
				e.printStackTrace();
			}
		}
    }
	
	
	// 环形图  数据集
    public static PieDataset getDataAnnularUtil(double[] data,String[] datadescription){
        if (data != null && datadescription != null){
            if (data.length == datadescription.length){
                DefaultPieDataset dataset = new DefaultPieDataset();
                for (int i = 0; i < data.length; i++){
                	dataset.setValue(datadescription[i],data[i]);
                }
                return dataset;
            }
        }
        return null;
    }
    
	// 饼图 数据集
	public static PieDataset getDataPieSetByUtil(double[] data,
	        String[] datadescription){

		if (data != null && datadescription != null){
			if (data.length == datadescription.length){
				DefaultPieDataset dataset = new DefaultPieDataset();
				for (int i = 0; i < data.length; i++){
					dataset.setValue(datadescription[i], data[i]);
				}
				return dataset;
			}
		}
		return null;
	}
    
    //柱状图,折线图 数据集
 	public static CategoryDataset getBarData(double[][] data, String[] rowKeys,String[] columnKeys){
 			return DatasetUtilities
 			        .createCategoryDataset(rowKeys, columnKeys, data);
 	}
    
    
    /**
	 * 判断文件夹是否存在,如果不存在则新建
	 * @param chartPath
	 */
	private static  void isChartPathExist(String chartPath){
		File file = new File(chartPath);
		if (!file.exists()){
			file.mkdirs();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值