java 实现各种数据统计图

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27843945/article/details/76241378

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.XYBoxAnnotation;
import org.jfree.chart.annotations.XYTextAnnotation;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.data.time.Day;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.DefaultXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.TextAnchor;


public class ChartsImgUtil {


//数据折线图
    public static String createTimeXYChar(String chartTitle, String x, String y,
            CategoryDataset xyDataset, String charName,int width,int height) {


        JFreeChart chart = ChartFactory.createLineChart(chartTitle, x, y,xyDataset, PlotOrientation.VERTICAL, true, true,false);




        chart.setTextAntiAlias(false);//必须设置文本抗锯齿为false,防止乱码
        chart.setBackgroundPaint(Color.WHITE);
        // 设置图标题的字体重新设置title
        Font font = new Font("隶书", Font.BOLD, 20);
        TextTitle title = new TextTitle(chartTitle);
        title.setFont(font);
        chart.setTitle(title);
        // 设置面板字体
        Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);
        
        chart.setBackgroundPaint(Color.WHITE);
        
        CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
        // x轴 // 分类轴网格是否可见
        categoryplot.setDomainGridlinesVisible(true);
        // y轴 //数据轴网格是否可见
        categoryplot.setRangeGridlinesVisible(true);
        
        categoryplot.setRangeGridlinePaint(Color.WHITE);// 虚线色彩
        
        categoryplot.setDomainGridlinePaint(Color.WHITE);// 虚线色彩
        
        categoryplot.setBackgroundPaint(Color.lightGray);
        
        // 设置轴和面板之间的距离
        // categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));


     // 设置X轴
        CategoryAxis domainAxis = categoryplot.getDomainAxis();
        


        domainAxis.setLabelFont(labelFont);// 轴标题
        
        domainAxis.setTickLabelFont(labelFont);// 轴数值


        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 45度倾斜
        // 设置距离图片左端距离
        domainAxis.setLowerMargin(0.0);
        // 设置距离图片右端距离
        domainAxis.setUpperMargin(0.0);
        
        
        //是否显示x轴刻度值
        //domainAxis.setTickLabelsVisible(true);     
       


      // 设置Y轴
        NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
        numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        numberaxis.setAutoRangeIncludesZero(true);
        numberaxis.setLabelFont(labelFont);
          
        // 获得renderer 注意这里是下嗍造型到lineandshaperenderer!!
        LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer();
        
        //设置数据点为圆形(x为上下偏离,y为左右偏离,w为圆形左右距离,h为圆形上下距离)  
        lineandshaperenderer.setSeriesShape(0,new Ellipse2D.Double(-1.0,-1.0,2.0, 2.0));  


        lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见
        
        lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见


        // 显示折点数据
        // lineandshaperenderer.setBaseItemLabelGenerator(new
        // StandardCategoryItemLabelGenerator());
        // lineandshaperenderer.setBaseItemLabelsVisible(true);
        
        FileOutputStream fos_jpg = null;
        try {
            isChartPathExist(CHART_PATH);
            String chartName = CHART_PATH + charName;
            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();
                System.out.println("创建成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    
    //日期折线图
    public static String genLineChart(String chartext,String x,String y,TimeSeriesCollection lineDataset,String path)throws Exception{
        
       
        
        JFreeChart chart=ChartFactory.createTimeSeriesChart(chartext, x, y, lineDataset, true, true, true);
        
        chart.setTextAntiAlias(false);//必须设置文本抗锯齿为false,防止乱码
        chart.setBackgroundPaint(Color.WHITE);
        // 设置图标题的字体重新设置title
        Font font = new Font("隶书", Font.BOLD, 20);
        TextTitle title = new TextTitle(chartext);
        title.setFont(font);
        chart.setTitle(title);
        // 设置面板字体
        Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);
        
        chart.setBackgroundPaint(Color.WHITE);
        
        //设置时间轴的范围。
        XYPlot plot = (XYPlot) chart.getPlot(); 
        DateAxis dateaxis = (DateAxis)plot.getDomainAxis();
        dateaxis.setLabelFont(labelFont);
        dateaxis.setTickLabelFont(labelFont);
        dateaxis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));
       
        //右边的数字设置x轴的间隔
        dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH,2)); 
        //dateaxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 45度倾斜
      
        
        //设置曲线是否显示数据点
        XYLineAndShapeRenderer xylinerenderer = (XYLineAndShapeRenderer)plot.getRenderer();
        xylinerenderer.setBaseShapesVisible(true); 
        
        //设置曲线显示各数据点的值
        XYItemRenderer xyitem = plot.getRenderer(); 
        xyitem.setBaseItemLabelsVisible(true);
        xyitem.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER)); 
        xyitem.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
        xyitem.setBaseItemLabelFont(new Font("Dialog", 1, 12)); 
        plot.setRenderer(xyitem);
        
        
        /*String fileName=ServletUtilities.saveChartAsPNG(chart, 700, 500, session);*/
        String chartName = "";
FileOutputStream fos_jpg = null;
try {
// 文件夹不存在则创建
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
chartName = path + File.separator + new Date().getTime() + ".png";
fos_jpg = new FileOutputStream(chartName);
ChartUtilities.writeChartAsPNG(fos_jpg, chart, 700, 400);

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos_jpg.close();
} catch (Exception e) {
e.printStackTrace();
}
return chartName;
}
        
    }
    
    
        //散点图展示
    public static String createPointChart(XYDataset xydataset,  String title, String domainName, String rangeName, String noDateMsg,  String path){
     
        JFreeChart jfreechart = ChartFactory.createScatterPlot(title,  
        domainName, rangeName, xydataset, PlotOrientation.VERTICAL, true, false,  
                false);  
        jfreechart.setBackgroundPaint(Color.white);  
        jfreechart.setBorderPaint(Color.GREEN);  
        jfreechart.setBorderStroke(new BasicStroke(1.5f));  
        jfreechart.getTitle().setFont((new Font("隶书", Font.CENTER_BASELINE, 20)));
        jfreechart.getLegend().setItemFont(new Font("隶书", Font.CENTER_BASELINE, 15));// 设置图例类别字体
        
        XYPlot xyplot = (XYPlot) jfreechart.getPlot();  
        xyplot.setNoDataMessage(noDateMsg);  
        xyplot.setNoDataMessageFont(new Font("隶书", Font.BOLD, 14));  
        //xyplot.setNoDataMessagePaint(new Color(87, 149, 117));  
  
        xyplot.setBackgroundPaint(new Color(255, 253, 246));  
        ValueAxis vaaxis = xyplot.getDomainAxis();  
        vaaxis.setAxisLineStroke(new BasicStroke(1.5f));  
  
        ValueAxis va = xyplot.getDomainAxis(0);  
        va.setAxisLineStroke(new BasicStroke(1.5f));  
  
        va.setAxisLineStroke(new BasicStroke(1.5f)); // 坐标轴粗细  
        va.setAxisLinePaint(new Color(215, 215, 215)); // 坐标轴颜色  
        xyplot.setOutlineStroke(new BasicStroke(1.5f)); // 边框粗细  
        va.setLabelPaint(new Color(10, 10, 10)); // 坐标轴标题颜色  
        va.setTickLabelPaint(new Color(102, 102, 102)); // 坐标轴标尺值颜色  
        ValueAxis axis = xyplot.getRangeAxis();  
        vaaxis.setLabelFont(new Font("隶书", Font.CENTER_BASELINE, 15));
        axis.setAxisLineStroke(new BasicStroke(1.5f));  
  
        XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyplot  
                .getRenderer();  
        xylineandshaperenderer.setSeriesOutlinePaint(0, Color.WHITE);  
        xylineandshaperenderer.setUseOutlinePaint(true);  
        NumberAxis numberaxis = (NumberAxis) xyplot.getDomainAxis();  
        numberaxis.setAutoRangeIncludesZero(false);  
        numberaxis.setTickMarkInsideLength(2.0F);  
        numberaxis.setTickMarkOutsideLength(0.0F);  
        numberaxis.setAxisLineStroke(new BasicStroke(1.5f));  
       // numberaxis.setUpperBound(maxpress); 最大值设置 
       // numberaxis.setLowerBound();最小值设置
        NumberAxis numberaxis1 = (NumberAxis) xyplot.getRangeAxis();  
        numberaxis1.setTickMarkInsideLength(2.0F);  
        numberaxis1.setTickMarkOutsideLength(0.0F);  
        numberaxis1.setUpperBound(150d);  
        numberaxis1.setLowerBound(35);  
        numberaxis1.setAxisLineStroke(new BasicStroke(1.5f));  
        numberaxis1.setLabelFont(new Font("隶书", Font.CENTER_BASELINE, 15));
  
        XYBoxAnnotation box = new XYBoxAnnotation(0, 0, 89, 59); //正常血压所在区域内边界  
        XYBoxAnnotation box1 = new XYBoxAnnotation(0, 0, 119, 79);//高血压前期所在区域内边界  
        XYBoxAnnotation box2 = new XYBoxAnnotation(0, 0, 139, 89);//高血压一期所在区域内边界  
        XYBoxAnnotation box3 = new XYBoxAnnotation(0, 0, 159, 99);//高血压二期所在区域内边界  
        XYTextAnnotation text1 = new XYTextAnnotation("nomal", 70, 62.5);//标识“正常”  
        XYTextAnnotation text = new XYTextAnnotation("fore", 70, 82.5);//“高血压前期”  
        XYTextAnnotation text2 = new XYTextAnnotation("one", 70, 91.5);//“高血压一期”  
        XYTextAnnotation text3 = new XYTextAnnotation("two", 70, 101.5);//“高血压二期”  
  
          
        //将上面的边界线条,说明文字加入到xyplot中。  
        xyplot.addAnnotation(box);  
        xyplot.addAnnotation(box1);  
        xyplot.addAnnotation(box2);  
        xyplot.addAnnotation(box3);  
  
        xyplot.addAnnotation(text);  
        xyplot.addAnnotation(text1);  
        xyplot.addAnnotation(text2);  
        xyplot.addAnnotation(text3);  
        String chartName = "";
FileOutputStream fos_jpg = null;
try {
// 文件夹不存在则创建
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
chartName = path + File.separator + new Date().getTime() + ".png";
fos_jpg = new FileOutputStream(chartName);
ChartUtilities.writeChartAsPNG(fos_jpg, jfreechart, 700, 400);

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos_jpg.close();
} catch (Exception e) {
e.printStackTrace();
}
return chartName;
}
    }


    
    //饼状图
    public static String createPieChart3D(String title, PieDataset dataset,String path) {
    JFreeChart chart = ChartFactory.createPieChart3D(title, dataset, true,
    true, Locale.CHINA);


    // 使下面的说明标签字体清晰,类似于去锯齿的效果
    chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,
    RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    chart.setTextAntiAlias(false);
    // 图片背景色
    chart.setBackgroundPaint(Color.white);


    // 设置图标题的字体重新设置title(否组有些版本Title会出现乱码)
    chart.getTitle().setFont((new Font("隶书", Font.CENTER_BASELINE, 20)));


    // 设置图例(Legend)上的文字(//底部的字体)
    chart.getLegend().setItemFont(new Font("隶书", Font.CENTER_BASELINE, 15));


    PiePlot3D plot = (PiePlot3D) chart.getPlot();
    // 图片中显示百分比:默认方式


    // 指定饼图轮廓线的颜色
    plot.setBaseSectionOutlinePaint(Color.BLACK);
    plot.setBaseSectionPaint(Color.BLACK);


    // 设置无数据时的信息
    plot.setNoDataMessage("无对应的数据,请重新查询。");


    // 设置无数据时的信息显示颜色
    plot.setNoDataMessagePaint(Color.red);


    // 图片中显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
    "{0}={1}({2})", NumberFormat.getNumberInstance(),
    new DecimalFormat("0.00%")));
    // 图例显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例
    plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator(
    "{0}({2})"));


    plot.setLabelFont(new Font("隶书", Font.TRUETYPE_FONT, 12));


    // 指定图片的透明度(0.0-1.0)
    plot.setForegroundAlpha(0.65f);
    // 指定显示的饼图上圆形(false)还椭圆形(true)
    plot.setCircular(false, true);


    // 设置第一个 饼块section 的开始位置,默认是12点钟方向
    plot.setStartAngle(90);


    // 设置分饼颜色(不设置它会自己设置)
    // plot.setSectionPaint(pieKeys[0], new Color(244, 194, 144));
    // plot.setSectionPaint(pieKeys[1], new Color(144, 233, 144));


    // 把饼图生成图片
    String chartName = "";
    FileOutputStream fos_jpg = null;
    try {
    // 文件夹不存在则创建
    File file = new File(path);
    if (!file.exists()) {
    file.mkdirs();
    }
    chartName = path + File.separator + new Date().getTime() + ".png";
    fos_jpg = new FileOutputStream(chartName);
    // 高宽的设置影响椭圆饼图的形状
    ChartUtilities.writeChartAsPNG(fos_jpg, chart, 700, 400);


    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    fos_jpg.close();// http://[email protected]
    } catch (Exception e) {
    e.printStackTrace();
    }
    return chartName;
    }
    }
   
    
    //3d柱状图展示
    public static String createBarChart(String title, String domainName,String rangeName, CategoryDataset dataset, String path) {
    JFreeChart chart = ChartFactory.createBarChart3D(title,domainName ,
    rangeName, dataset, PlotOrientation.VERTICAL, true, true, false);
    CategoryPlot plot = chart.getCategoryPlot();
    chart.getTitle().setFont((new Font("隶书", Font.CENTER_BASELINE, 20))); // 设置标题字体
    // 设置网格背景颜色
    plot.setBackgroundPaint(Color.white);
    // 设置网络竖线颜色
    plot.setDomainGridlinePaint(Color.pink);
    // 显示每个柱的数值,并修改该数字的字体属性
    BarRenderer3D renderer = new BarRenderer3D();
    renderer
    .setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    renderer.setBaseItemLabelsVisible(true);
    // 默认的数字显示在柱子中,通过以下两句调整数字的显示
    // 注意,此句很关键,若无此句,那数字的显示会覆盖,给人数字没有显示出来的问题
    renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
    ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
    renderer.setItemLabelAnchorOffset(10D);
    // 设置每个地区所包含的平行柱的之间的距离
    // renderer.setItemMargin(0.3);
    plot.setRenderer(renderer);


    // 设置位置
    plot.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);
    // 将默认的左边的放到右方
    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
    NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();
    CategoryAxis domainAxis = plot.getDomainAxis();
    // 图表标题
    Font font = new Font("宋体", Font.BOLD, 16);
    chart.setTitle(title); // 标题


    // X轴乱码
    // X轴坐标上的文字:
    domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));
    // X轴坐标标题
    domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));
    // Y轴坐标上的文字
    numberaxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));
    // Y轴坐标标题
    numberaxis.setLabelFont(new Font("黑体", Font.PLAIN, 12));
    // 图表底部乱码
    chart.getLegend().setItemFont(new Font("黑体", Font.PLAIN, 12));
    String chartName = "";
    FileOutputStream fos_jpg = null;
    try {
    // 文件夹不存在则创建
    File file = new File(path);
    if (!file.exists()) {
    file.mkdirs();
    }
    chartName = path + File.separator + new Date().getTime() + ".png";
    fos_jpg = new FileOutputStream(chartName);
    // 高宽的设置影响椭圆饼图的形状
    ChartUtilities.writeChartAsPNG(fos_jpg, chart, 700, 400);


    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    fos_jpg.close();// http://[email protected]
    } catch (Exception e) {
    e.printStackTrace();
    }
    return chartName;
    }
    }
   
   
    //条形图展示
    public static String createCategoryDataset(String title, String domainName,
    String rangeName, DefaultCategoryDataset dataset, String path) {
    JFreeChart chart = ChartFactory.createBarChart(title, domainName, rangeName, dataset,
    PlotOrientation.VERTICAL, true, true, false);
    chart.getTitle().setFont((new Font("隶书", Font.CENTER_BASELINE, 20))); // 设置标题字体
    CategoryPlot plot = chart.getCategoryPlot();// 获得图表区域对象
    // 设置图表的纵轴和横轴org.jfree.chart.axis.CategoryAxis
    CategoryAxis domainAxis = plot.getDomainAxis();
    NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();
    TextTitle textTitle = chart.getTitle();
    textTitle.setFont(new Font("黑体", Font.PLAIN, 20));
    domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));
    domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));
    numberaxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));
    numberaxis.setLabelFont(new Font("黑体", Font.PLAIN, 12));
    chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));


    String chartName = "";
    FileOutputStream fos_jpg = null;
    try {
    // 文件夹不存在则创建
    File file = new File(path);
    if (!file.exists()) {
    file.mkdirs();
    }
    chartName = path + File.separator + new Date().getTime() + ".png";
    fos_jpg = new FileOutputStream(chartName);
    // 高宽的设置影响椭圆饼图的形状
    ChartUtilities.writeChartAsPNG(fos_jpg, chart, 700, 400);


    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    fos_jpg.close();// http://[email protected]
    } catch (Exception e) {
    e.printStackTrace();
    }
    return chartName;
    }
    }
    
    
    //3D折线图
    public static String createLineChart(String title, String domainAxisName,String rangeAxisName, DefaultCategoryDataset ds, String path) {
    JFreeChart chart = ChartFactory.createLineChart3D(title, domainAxisName,
    rangeAxisName, ds, PlotOrientation.VERTICAL, // 绘制方向
    true, // 显示图例
    true, // 采用标准生成器
    false // 是否生成超链接
    );
    chart.getTitle().setFont((new Font("隶书", Font.CENTER_BASELINE, 20))); // 设置标题字体
    chart.getLegend().setItemFont(new Font("隶书", Font.CENTER_BASELINE, 15));// 设置图例类别字体
    // 获取绘图区对象
    CategoryPlot plot = chart.getCategoryPlot();
    plot.setBackgroundPaint(Color.LIGHT_GRAY); // 设置绘图区背景色
    plot.setRangeGridlinePaint(Color.WHITE); // 设置水平方向背景线颜色
    plot.setRangeGridlinesVisible(true);// 设置是否显示水平方向背景线,默认值为true
    plot.setDomainGridlinePaint(Color.WHITE); // 设置垂直方向背景线颜色
    plot.setDomainGridlinesVisible(true); // 设置是否显示垂直方向背景线,默认值为false


    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setLabelFont(new Font("隶书", Font.CENTER_BASELINE, 15)); // 设置横轴字体
    // domainAxis.setTickLabelFont(font);// 设置坐标轴标尺值字体
    domainAxis.setLowerMargin(0.01);// 左边距 边框距离
    domainAxis.setUpperMargin(0.06);// 右边距 边框距离,防止最后边的一个数据靠近了坐标轴。
    domainAxis.setMaximumCategoryLabelLines(2);


    ValueAxis rangeAxis = plot.getRangeAxis();
    rangeAxis.setLabelFont(new Font("隶书", Font.CENTER_BASELINE, 15));
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());// Y轴显示整数
    rangeAxis.setAutoRangeMinimumSize(1); // 最小跨度
    rangeAxis.setUpperMargin(0.18);// 上边距,防止最大的一个数据靠近了坐标轴。
    rangeAxis.setLowerBound(0); // 最小值显示0
    rangeAxis.setAutoRange(false); // 不自动分配Y轴数据
    rangeAxis.setTickMarkStroke(new BasicStroke(1.6f)); // 设置坐标标记大小
    rangeAxis.setTickMarkPaint(Color.BLACK); // 设置坐标标记颜色


    // 获取折线对象
    LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot
    .getRenderer();
    BasicStroke realLine = new BasicStroke(1.8f); // 设置实线
    // 设置虚线
    float dashes[] = { 5.0f };
    BasicStroke brokenLine = new BasicStroke(2.2f, // 线条粗细
    BasicStroke.CAP_ROUND, // 端点风格
    BasicStroke.JOIN_ROUND, // 折点风格
    8f, dashes, 0.6f);


    plot.setNoDataMessage("无对应的数据,请重新查询。");
    plot.setNoDataMessagePaint(Color.RED);// 字体颜色
    // 把饼图生成图片
    String chartName = "";
    FileOutputStream fos_jpg = null;
    try {
    // 文件夹不存在则创建
    File file = new File(path);
    if (!file.exists()) {
    file.mkdirs();
    }
    chartName = path + File.separator + new Date().getTime() + ".png";
    fos_jpg = new FileOutputStream(chartName);
    // 高宽的设置影响椭圆饼图的形状
    ChartUtilities.writeChartAsPNG(fos_jpg, chart, 700, 400);


    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    fos_jpg.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return chartName;
    }
    }
    
    
    /** 
     * 判断文件夹是否存在,如果不存在则新建 
     * @param chartPath 
     */  
    private static void isChartPathExist(String chartPath) {  
        File file = new File(chartPath);  
        if (!file.exists()) {  
            file.mkdirs();  
        // log.info("CHART_PATH="+CHART_PATH+"create.");  
        }  
    }  
    // 柱状图,折线图 数据集  
    public static CategoryDataset getBarData(double[][] data, String[] rowKeys, Double[] columnKeys) {  
        return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data);  
  
    } 
    /*//儒略日 转换成正常日期
    public static Date juLianToDate(int date) {
      int year = (date / 1000) + 1900;
      int dayOfYear = date % 1000;
   
      Calendar calendar = Calendar.getInstance();
      calendar.set(Calendar.YEAR, year);
      calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
   
      return calendar.getTime();
    }
    //将当前日期转换成JuLian
    public static int dateToJuLian(Date date) {
       Calendar calendar = Calendar.getInstance();
       calendar.setTime(date);
       int year = calendar.get(Calendar.YEAR) - 1900;
       int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR); 
       return year * 1000 + dayOfYear;
     }
    
    public static Double GetMJd(Date dt)
    {
        long I = dt.getYear(), J = dt.getMonth(), K = dt.getDay();
        //求出给定年(I),月(J),日(K)的儒略日:
        long jd = K - 32075 + 1461 * (I + 4800 + (J - 14) / 12) / 4 + 367 * (J - 2 - (J -            14) / 12 * 12) / 12 - 3 * ((I + 4900 + (J - 14) / 12) / 100) / 4;
        Double mjdSt = jd - 2400000.5;
        String mjdStr=mjdSt.toString();
        int x = mjdStr.indexOf(".");
        if (x == -1)
        {
            return  Double.parseDouble(mjdStr);


        }
        else
        {
            mjdStr = mjdStr.substring(0, x);
            return  Double.parseDouble(mjdStr);
        }
    }*/
    
private static final String CHART_PATH = "E:/chartsimg/";


public static void main(String[] args) throws Exception {
    /* double[][] data = new double[1][5];  //定义一行五列数组
    data[0][0]=-10; //第一行第一列
    data[0][1]=-15; //第一行第二列
    data[0][2]=-22; //第一行第三列
    data[0][3]=-29; //第一行第四列
    data[0][4]=-41; //第一行第五列
         String[] rowKeys = {"test","梨子", "葡萄"};  
         String[] columnKeys = {"57616", "57617", "57618", "57619", "57620"}; */


  //折线图展示
double[][] data = new double[][]{  
             {13.9, 81.2, 17.9, 14.2, 5.4, -1.4, -7, -6.8, 
             -6.2, 50.9, 45.9, 40.3, 18.4, 21.1,15.9, 30.1, 
             90.0, 2.5, 59.3, 61.3, 61.8, 73.7, 43, 100},  
             /*{325, 521, 210, 340, 106},  
             {332, 256, 523, 240, 526} */
         };  
  String[] rowKeys = {"test"/*,"梨子", "葡萄"*/};
  Double[] columnKeys = {57866.423610, 57866.434720, 57866.445830, 57866.456940, 57866.468060,57866.479170, 57866.490280, 
          57866.501390, 57866.512500, 57866.523610, 57866.534720, 57866.545830, 57866.556940, 57866.568060, 57866.579170, 
          57866.590280, 57866.601390, 57866.612500, 57866.623610, 57866.634720, 57866.645830, 57866.656940, 57866.668060, 57866.679170};  
         CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);
  createTimeXYChar("  ", "时间(mjd)", " 纳秒(ns)",dataset,"demo.png",500,500);
    
    
 
  //3d折线图展示       
  /*DefaultCategoryDataset ds = new DefaultCategoryDataset();  
  ds.addValue(90, "温度", "2011-01-01");
  ds.addValue(100, "温度", "2011-01-02");
  ds.addValue(80, "温度", "2011-01-03");
  ds.addValue(120, "温度", "2011-01-04");
 
  ds.addValue(130, "湿度", "2011-01-01");
  ds.addValue(100, "湿度", "2011-01-02");
  ds.addValue(150, "湿度", "2011-01-03");
  ds.addValue(140, "湿度", "2011-01-04");
  createLineChart("3d折线图", "ss", "ss", ds, CHART_PATH);*/
 
 
 
  //饼状图展示
  /*String[] keys = { "王晓博", "李冰", "牛根生", "李开复", "马云", "其它" };
  double[] data2 = { 60, 60, 55, 77, 80, 50 };
  DefaultPieDataset dataset2 = new DefaultPieDataset();
  for (int i = 0; i < keys.length; i++) {
   dataset2.setValue(keys[i], data2[i]);
  }
  createPieChart3D("3d饼状图", dataset2, CHART_PATH);*/
 
 
   
  //散点图展示
  /*double[][] data1 = new double[2][5];
  DefaultXYDataset xydataset = new DefaultXYDataset();  
  data1[0][0] = 80;
  data1[1][0] = 88;
  data1[0][1] = 82;
  data1[1][1] = 90;
  data1[0][2] = 98;
  data1[1][2] = 67;
  data1[0][3] = 110;
  data1[1][3] = 120;
  data1[0][4] = 122;
  data1[1][4] = 132;
  xydataset.addSeries("温度", data1); 
  createPointChart(xydataset, "", "", "", "", CHART_PATH);*/
 
   
 
  //3d柱状图展示
  /* double[][] data11 = new double[][] { { 1310, 1220, 1110, 1000, 666 },
  { 720, 700, 680, 640, 777 }, { 1130, 1020, 980, 800, 888 },
  { 440, 400, 360, 300, 999 }, { 400, 400, 400, 400, 555 } };
  String[] rowKeys1 = { "猪肉", "牛肉", "鸡肉", "鱼肉", "羊肉" };
  String[] columnKeys1 = { "襄城", "樊城", "襄州", "东津", "鱼梁州" };
  CategoryDataset dataset1 = DatasetUtilities.createCategoryDataset(
  rowKeys1, columnKeys1, data11);
    createBarChart("", "", "", dataset1, CHART_PATH);*/
 
 
 
 
    //条形图展示
  /* DefaultCategoryDataset dataset21 = new DefaultCategoryDataset();
  dataset21.addValue(100, "struts1.2", "张三");
  dataset21.addValue(200, "struts2.x", "张三");
  dataset21.addValue(300, "webwork", "张三");
  dataset21.addValue(400, "spring", "张三");
  dataset21.addValue(100, "struts1.2", "李四");
  dataset21.addValue(200, "struts2.x", "李四");
  dataset21.addValue(300, "webwork", "李四");
  dataset21.addValue(400, "spring", "李四");  //dataset.addValue(-20, "Ext JS", "Jan")负向坐标
  createCategoryDataset("", "", "", dataset21, CHART_PATH);*/
 
 
  //日期折线图
     TimeSeries timeSeries=new TimeSeries("", Day.class);
     timeSeries.add(new Day(1, 1,2013), 100);
     timeSeries.add(new Day(1, 2,2013), 200);
     timeSeries.add(new Day(1, 3,2013), 300);
     timeSeries.add(new Day(1, 4,2013), 400);
     timeSeries.add(new Day(1, 5,2013), 560);
     timeSeries.add(new Day(1, 6,2013), 600);
     timeSeries.add(new Day(1, 7,2013), 750);
     timeSeries.add(new Day(1, 8,2013), 890);
     timeSeries.add(new Day(1, 9,2013), 120);
     timeSeries.add(new Day(1, 10,2013), 400);
     timeSeries.add(new Day(1, 11,2013), 1200);
     timeSeries.add(new Day(1, 12,2013), 1600);
     TimeSeriesCollection lineDataset=new TimeSeriesCollection();
     lineDataset.addSeries(timeSeries);
     genLineChart("", "", "", lineDataset, CHART_PATH);
 
   
   /*String getImageStr = Base64ImgUtil.GetImageStr("E:/chartsimg/demo.png");
   System.out.println(getImageStr);*/
  /*Date juLianToDate = juLianToDate(117185);
  System.out.println(juLianToDate);


  SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    try {
Date parse = formatter.parse("2017-04-13 12:42:00");
Date d=new Date();
Double getMJd = GetMJd(d);
  int dateToJuLian = dateToJuLian(d);
  System.out.println(dateToJuLian+"---"+d+"--"+getMJd);
    } catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/  
}

}


猜你喜欢

转载自blog.csdn.net/qq_27843945/article/details/76241378