工具类

CreatLineChart.java

package DrawLine;import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;import javax.swing.SwingUtilities;import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PieLabelLinkStyle;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.StandardXYBarPainter;
import org.jfree.data.category.DefaultCategoryDataset;
//import org.jfree.ui.RectangleInsets;
//import org.jfree.chart.ui.RectangleInsets;
import org.jfree.ui.TextAnchor;/*** @Title:创建折线图* @author* @since   JDK1.6* @history*/
public class CreatLineChart {/*** Jfreechart工具类* <p>* 解决中午乱码问题<br>* 用来创建类别图表数据集、创建饼图数据集、时间序列图数据集<br>* 用来对柱状图、折线图、饼图、堆积柱状图、时间序列图的样式进行渲染<br>* 设置X-Y坐标轴样式* <p>**/private static String NO_DATA_MSG = "数据加载失败";private static Font FONT = new Font("宋体", Font.PLAIN, 12);public static Color[] CHART_COLORS = {new Color(31,129,188), new Color(92,92,97), new Color(144,237,125), new Color(255,188,117),new Color(153,158,255), new Color(255,117,153), new Color(253,236,109), new Color(128,133,232),new Color(158,90,102),new Color(255, 204, 102) };//颜色/*** 静态代码块*/static {//        setChartTheme();}/*** 无参构造器*/public CreatLineChart() {}/** TODO  可以通过调用这个方法, 提供对应格式的参数即可生成图片,并存在指定位置* 生成一个这先出并保存为png格式,* @param title 图片标题* @param xtitle x轴标题* @param ytitle y轴标题* @param filepath 文件路径+文件名* @param categorie 横坐标类型* @param series 数据内容* @param width 图片宽度* @param height 图片高度* @throws Exception*/public  static void CreateNewLineChartForPng(String title,String xtitle,String ytitle,String filepath,List<String> categorie,List<Serie> series,int width,int height) throws Exception{ChartPanel  chartPanel = new CreatLineChart().createChart(title, xtitle, ytitle, categorie,series);//将图片保存为png格式saveAsFile(chartPanel.getChart(),filepath,width,height);}/*** 中文主题样式 解决乱码*/
//    public static void setChartTheme() {//        // 设置中文主题样式 解决乱码
//        StandardChartTheme chartTheme = new StandardChartTheme("CN");
//        // 设置标题字体
//        chartTheme.setExtraLargeFont(FONT);
//        // 设置图例的字体
//        chartTheme.setRegularFont(FONT);
//        // 设置轴向的字体
//        chartTheme.setLargeFont(FONT);
//        chartTheme.setSmallFont(FONT);
//        chartTheme.setTitlePaint(new Color(51, 51, 51));
//        chartTheme.setSubtitlePaint(new Color(85, 85, 85));
//
//        chartTheme.setLegendBackgroundPaint(Color.WHITE);// 设置标注
//        chartTheme.setLegendItemPaint(Color.BLACK);//
//        chartTheme.setChartBackgroundPaint(Color.WHITE);
//        // 绘制颜色绘制颜色.轮廓供应商
//        // paintSequence,outlinePaintSequence,strokeSequence,outlineStrokeSequence,shapeSequence
//
//        Paint[] OUTLINE_PAINT_SEQUENCE = new Paint[] { Color.WHITE };
//        // 绘制器颜色源
//        DefaultDrawingSupplier drawingSupplier = new DefaultDrawingSupplier(CHART_COLORS, CHART_COLORS, OUTLINE_PAINT_SEQUENCE,
//                DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
//                DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
//        chartTheme.setDrawingSupplier(drawingSupplier);
//
//        chartTheme.setPlotBackgroundPaint(Color.WHITE);// 绘制区域
//        chartTheme.setPlotOutlinePaint(Color.WHITE);// 绘制区域外边框
//        chartTheme.setLabelLinkPaint(new Color(8, 55, 114));// 链接标签颜色
//        chartTheme.setLabelLinkStyle(PieLabelLinkStyle.CUBIC_CURVE);
//
//        chartTheme.setAxisOffset(new RectangleInsets(5, 12, 5, 12));
//        chartTheme.setDomainGridlinePaint(new Color(192, 208, 224));// X坐标轴垂直网格颜色
//        chartTheme.setRangeGridlinePaint(new Color(192, 192, 192));// Y坐标轴水平网格颜色
//
//        chartTheme.setBaselinePaint(Color.WHITE);
//        chartTheme.setCrosshairPaint(Color.BLUE);// 不确定含义
//        chartTheme.setAxisLabelPaint(new Color(51, 51, 51));// 坐标轴标题文字颜色
//        chartTheme.setTickLabelPaint(new Color(67, 67, 72));// 刻度数字
//        chartTheme.setBarPainter(new StandardBarPainter());// 设置柱状图渲染
//        chartTheme.setXYBarPainter(new StandardXYBarPainter());// XYBar 渲染
//
//        chartTheme.setItemLabelPaint(Color.black);
//        chartTheme.setThermometerPaint(Color.white);// 温度计
//
//        ChartFactory.setChartTheme(chartTheme);
//    }/*** 创建类别数据集合*/public static DefaultCategoryDataset createDefaultCategoryDataset(List<Serie> series, String[] categories) {DefaultCategoryDataset dataset = new DefaultCategoryDataset();for (Serie serie : series) {String name = serie.getName();Vector<Object> data = serie.getData();if (data != null && categories != null && data.size() == categories.length) {for (int index = 0; index < data.size(); index++) {String value = data.get(index) == null ? "" : data.get(index).toString();if (isPercent(value)) {value = value.substring(0, value.length() - 1);}if (isNumber(value)) {dataset.setValue(Double.parseDouble(value), name, categories[index]);}}}}return dataset;}/*** 设置图例无边框,默认黑色边框*/public static void setLegendEmptyBorder(JFreeChart chart) {chart.getLegend().setFrame(new BlockBorder(Color.WHITE));}/*** 是不是一个%形式的百分比** @param str* @return*/public static boolean isPercent(String str) {return str != null ? str.endsWith("%") && isNumber(str.substring(0, str.length() - 1)) : false;}/*** 是不是一个数字** @param str* @return*/public static boolean isNumber(String str) {return str != null ? str.matches("^[-+]?(([0-9]+)((([.]{0})([0-9]*))|(([.]{1})([0-9]+))))$") : false;}/*** 设置 折线图样式** @param plot* @param isShowDataLabels*            是否显示数据标签 默认不显示节点形状*/public static void setLineRender(CategoryPlot plot, boolean isShowDataLabels) {setLineRender(plot, isShowDataLabels, false);}/*** 设置折线图样式** @param plot* @param isShowDataLabels*            是否显示数据标签*/@SuppressWarnings("deprecation")public static void setLineRender(CategoryPlot plot, boolean isShowDataLabels, boolean isShapesVisible) {plot.setNoDataMessage(NO_DATA_MSG);
//        plot.setInsets(new RectangleInsets(10, 10, 0, 10), false);LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();renderer.setStroke(new BasicStroke(1.5F));//renderer.setSeriesStroke(1, new BasicStroke(0.00001F));if (isShowDataLabels) {renderer.setBaseItemLabelsVisible(true);renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator(StandardCategoryItemLabelGenerator.DEFAULT_LABEL_FORMAT_STRING,NumberFormat.getInstance()));renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE1, TextAnchor.BOTTOM_CENTER));// weizhi}renderer.setBaseShapesVisible(isShapesVisible);// 数据点绘制形状setXAixs(plot);setYAixs(plot);}/*** 设置类别图表(CategoryPlot) X坐标轴线条颜色和样式**/public static void setXAixs(CategoryPlot plot) {Color lineColor = new Color(31, 121, 170);plot.getDomainAxis().setAxisLinePaint(lineColor);// X坐标轴颜色plot.getDomainAxis().setTickMarkPaint(lineColor);// X坐标轴标记|竖线颜色}/*** 设置类别图表(CategoryPlot) Y坐标轴线条颜色和样式 同时防止数据无法显示**/public static void setYAixs(CategoryPlot plot) {Color lineColor = new Color(192, 208, 224);ValueAxis axis = plot.getRangeAxis();axis.setAxisLinePaint(lineColor);// Y坐标轴颜色axis.setTickMarkPaint(lineColor);// Y坐标轴标记|竖线颜色// 隐藏Y刻度axis.setAxisLineVisible(false);axis.setTickMarksVisible(false);// Y轴网格线条plot.setRangeGridlinePaint(new Color(192, 192, 192));plot.setRangeGridlineStroke(new BasicStroke(1));plot.getRangeAxis().setUpperMargin(0.1);// 设置顶部Y坐标轴间距,防止数据无法显示plot.getRangeAxis().setLowerMargin(0.1);// 设置底部Y坐标轴间距}/*** 必须设置文本抗锯齿*/public static void setAntiAlias(JFreeChart chart) {chart.setTextAntiAlias(false);}//-----------------------------------------------------------------------------------------------------------------/**** 折线图*       <p>*       创建图表步骤:<br/>*       1:创建数据集合<br/>*       2:创建Chart:<br/>*       3:设置抗锯齿,防止字体显示不清楚<br/>*       4:对柱子进行渲染,<br/>*       5:对其他部分进行渲染<br/>*       6:使用chartPanel接收<br/>*       </p>*///创建折线图图表public DefaultCategoryDataset createDataset(List<String> categorie,List<Serie> series) {// 标注类别String[] categories = categorie.toArray(new String[categorie.size()]);// 创建数据集合DefaultCategoryDataset dataset = CreatLineChart.createDefaultCategoryDataset(series, categories);return dataset;}/*** 创建折线图* @param title 折线图标题* @param xtitle x轴标题* @param ytitle y轴标题* @param categorie 横坐标类别* @param series 数据集* @return* @throws Exception*/public ChartPanel createChart(String title,String xtitle,String ytitle,List<String> categorie,List<Serie> series) throws Exception {// 2:创建Chart[创建不同图形]JFreeChart chart = ChartFactory.createLineChart(title, xtitle, ytitle, createDataset(categorie,series), PlotOrientation.VERTICAL, false, // legendfalse,          //Tooltipsfalse);// 3:设置抗锯齿,防止字体显示不清楚CreatLineChart.setAntiAlias(chart);// 抗锯齿// 4:对柱子进行渲染[[采用不同渲染]]CreatLineChart.setLineRender(chart.getCategoryPlot(), false,true);//// 5:对其他部分进行渲染CreatLineChart.setXAixs(chart.getCategoryPlot());// X坐标轴渲染CreatLineChart.setYAixs(chart.getCategoryPlot());// Y坐标轴渲染// 设置标注无边框
//        chart.getLegend().setFrame(new BlockBorder(Color.WHITE));// 6:使用chartPanel接收ChartPanel chartPanel = new ChartPanel(chart);return chartPanel;}/*** 主方法 用来测试  `* @param args*/public static void main(String[] args) {}/*** 将图表保存为PNG、JPEG图片* @param chart  折线图对象* @param outputPath 文件保存路径, 包含文件名* @param weight  宽* @param height 高* @throws Exception*/public static void saveAsFile(JFreeChart chart, String outputPath, int weight, int height)throws Exception {FileOutputStream out = null;File outFile = new File(outputPath);if (!outFile.getParentFile().exists()) {outFile.getParentFile().mkdirs();}out = new FileOutputStream(outputPath);// 保存为PNGChartUtilities.writeChartAsPNG(out, chart, weight, height);// 保存为JPEG// ChartUtilities.writeChartAsJPEG(out, chart, weight, height);out.flush();if (out != null) {try {out.close();} catch (IOException e) {// do nothinge.printStackTrace();}}}
}

JfreeChartUtils.java

package DrawLine;/*** @author tqf* @Description* @Version 1.0* @since 2022-06-06 15:32*/
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.manage.platform.manage_interface.service.monthlys.ExpoetService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYSplineRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.title.Title;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.category.IntervalCategoryDataset;
import org.jfree.data.gantt.Task;
import org.jfree.data.gantt.TaskSeries;
import org.jfree.data.gantt.TaskSeriesCollection;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.SeriesException;
import org.jfree.data.time.Day;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.ohlc.OHLCSeries;
import org.jfree.data.time.ohlc.OHLCSeriesCollection;
import org.jfree.data.xy.*;
import org.jfree.ui.HorizontalAlignment;
import org.jfree.ui.RectangleEdge;
import sun.misc.BASE64Encoder;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.Map;public class JfreeChartUtils {// 参考文章 https://www.jianshu.com/p/6c4f3832c396/*** 生成的图片存放地址*/public static String imagePath = "D://123//jfree";public static void main(String[] args) throws Exception {// 生成饼图testPie();// 生成折线图testLine();// 生成柱状图testBar();// 生成折线图 多条testCreateManyLineChart();// 生成3D柱状图bar3D();// 生成气泡图bubble();// 生成时序图sequenceDiagram();// 生成曲线图curve();// 生成环形图annular();// 生成区域图areaChart();// 生成气泡图2bubble2();// 生成分布图chartPanel();// 生成联合分类图 折线、柱状图chartPanel1();// 生成双轴图biaxial();// 生成甘特图createGanttChart();// 生成K线图kImage();// 生成柱状图-横向bar3DHx();}public static void testPie(){//如 果不使用Font,中文将显示不出来Font font = new Font("新宋体", Font.BOLD, 15);String name[] = {"录播主机","编码器","摄像机","流转码服务器","腾讯服务器"};double value[] = {1000,700,600,400,150};// 创建数据:饼状图就是名称和值(比例)Map<String, Double> map=new HashMap<String, Double>();for (int i=0;i<name.length;i++) {map.put(name[i],value[i]);}// 创建JFreeChartJFreeChart chart = createPieChart("故障设备类型比例", map, font);//在D盘目录下生成图片File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_饼图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);} catch (IOException e) {e.printStackTrace();}}public static void testLine(){//如 果不使用Font,中文将显示不出来Font font = new Font("新宋体", Font.BOLD, 15);// 创建数据Map<String, Map<String, Double>> datas =new HashMap<String, Map<String,Double>>();String monthArray[] = {"一月","二月","三月","四月","五月","六月","七月","八月"};double value[]= {20,30,25,50,40,25,50,40};for (int i=0; i<monthArray.length;i++) {Map<String, Double> map =new HashMap<String, Double>();map.put("故障数量", value[i]);datas.put(monthArray[i],map);}JFreeChart chart = createLineChart("故障数量-时间曲线", datas, "月份", "故障次数(次)", font);//在D盘目录下生成图片File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_折线图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);} catch (IOException e) {e.printStackTrace();}}public static void testBar(){//如 果不使用Font,中文将显示不出来Font font = new Font("新宋体", Font.BOLD, 15);// 创建数据Map<String, Map<String, Double>> datas =new HashMap<String, Map<String,Double>>();String name[] = {"设备网络掉线","CPU利用率高","磁盘占用高","掉线频率","内存使用率","访问量"};double value[] = {1000,1300,1200,1524,1247,6587};for (int i =0;i<name.length;i++) {Map<String, Double> map = new HashMap<String, Double>();map.put("故障数", value[i]);datas.put(name[i], map);}JFreeChart chart = createBarChart("故障类型比例",datas,"故障类型","数量单位(个)",font);//在D盘目录下生成图片File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_柱状图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);} catch (IOException e) {e.printStackTrace();}}public static void testCreateManyLineChart(){String[] title = {"成功量","失败量","异常"};String[] xValue = {"2021-01","2021-02","2021-03","2021-04","2021-05"};// 绘图数据集DefaultCategoryDataset dataSet = new DefaultCategoryDataset();Random r = new Random();for (int i =0;i<title.length;i++) {for (int j=0;j<xValue.length;j++) {// 生成[0,10]区间的整数int value = r.nextInt(10) * 2;dataSet.setValue(value,title[i],xValue[j]);}}JFreeChart chart = createManyLineChart(dataSet);//在D盘目录下生成图片File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_多条折线图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);} catch (IOException e) {e.printStackTrace();}}/*** 把jfreechart生成的图片转化为xml字符串,jfreechart图片导入word* @return* @throws IOException*/public static String getImageStr(String path) throws IOException {//方法 一,从硬盘上读取图片转化为xml_str
//      FileOutputStream fos_jpg = null;
//      // ObjectOutputStream oos = new ObjectOutputStream(baos);
//      try {//          fos_jpg = new FileOutputStream("D://bar.jpg");
//          // ChartUtilities.writeChartAsJPEG(fos_jpg,100,chart,400,300,null);
//          ChartUtilities.writeChartAsJPEG(fos_jpg, 1.0f, chart, 400, 300,
//                  null);
//      } finally {//          try {//              fos_jpg.close();
//          } catch (Exception e) {//          }
//      }InputStream in = null;byte[] data = null;try {in = new FileInputStream(path.substring(1));data = new byte[in.available()];in.read(data);in.close();} catch (IOException e) {e.printStackTrace();}BASE64Encoder encoder = new BASE64Encoder();String ss = encoder.encode(data);//        //方法二,通过url获取图片,此处需要服务器权限
//        Url url=new Url("http:\\....."+fileName);
//        InputStream is = url.openStream();
//                      。。。。
//
//
//
//        // 三,把图片保存在byte[]里面直接转换为xml_str
//        BASE64Encoder BASE64 = new BASE64Encoder();
//        ByteArrayOutputStream bas = new ByteArrayOutputStream();
//        try {//            ChartUtilities.writeChartAsJPEG(bas, 1.0f, chart, 400, 300, null);
//            bas.flush();
//            bas.close();
//        } catch (IOException e) {//            e.printStackTrace();
//        }
//        byte[] byteArray = bas.toByteArray();
//        try {//            InputStream is = new ByteArrayInputStream(byteArray);
//            byteArray = new byte[is.available()];
//            is.read(byteArray);
//            is.close();
//        } catch (IOException e) {//            e.printStackTrace();
//        }
//        String xml_img = BASE64.encode(byteArray);return ss;}static void sortMap(Map<String, Map<String, Double>> param) {TreeMap<String,  Map<String, Double>> paramTreeMap = new TreeMap<>(param);System.out.println(paramTreeMap);}/*** 生成饼图* @param title* @param data* @param font* @return*/public static JFreeChart createPieChart(String title, Map<String, Double> data, Font font) {try {Set<Map.Entry<String, Double>> set = data.entrySet();DefaultPieDataset pds = new DefaultPieDataset();Iterator iterator = set.iterator();Map.Entry entry;while (iterator.hasNext()) {entry = (Map.Entry) iterator.next();pds.setValue(entry.getKey().toString(), Double.parseDouble(entry.getValue().toString()));}// 生成一个饼图的图表:显示图表的标题、组装的数据、是否显示图例、是否生成贴士以及是否生成URL链接JFreeChart chart = ChartFactory.createPieChart(title, pds, true, false, true);// 设置图片标题的字体chart.getTitle().setFont(font);// 得到图块,准备设置标签的字体PiePlot plot = (PiePlot) chart.getPlot();//设置分裂效果,需要指定分裂出去的key
//            plot.setExplodePercent("摄像机", 0.1);  分裂效果,可选// 设置标签字体plot.setLabelFont(font);// 设置图例项目字体chart.getLegend().setItemFont(font);// 设置开始角度
//            plot.setStartAngle(new Float(3.14f / 2f));  开始角度,意义不大//设置plot的前景色透明度plot.setForegroundAlpha(0.7f);//设置plot的背景色透明度plot.setBackgroundAlpha(0.0f);//设置标签生成器(默认{0})//{0}:key {1}:value {2}:百分比 {3}:sumplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1})/{2}"));  // 一般在{1}后面加单位,如:{0}({1}次)/{2}//将内存中的图片写到本地硬盘
//            ChartUtilities.saveChartAsJPEG(new File("H:/a.png"), chart, 600, 300);// 标注位于上侧// chart.getLegend().setPosition(RectangleEdge.TOP);// 设置标注无边框chart.getLegend().setFrame(new BlockBorder(Color.WHITE));return chart;} catch (Exception e) {e.printStackTrace();return null;}}/*** 生成折线图* @param title* @param data* @param type* @param unit* @param font* @return*/public static JFreeChart createLineChart(String title, Map<String, Map<String, Double>> data, String type, String unit, Font font) {try {DefaultCategoryDataset ds = new DefaultCategoryDataset();Set<Map.Entry<String, Map<String, Double>>> set1 = data.entrySet();Iterator iterator1 = set1.iterator();Iterator iterator2;HashMap<String, Double> map;Set<Map.Entry<String, Double>> set2;Map.Entry entry1;Map.Entry entry2;while (iterator1.hasNext()) {entry1 = (Map.Entry) iterator1.next();map = (HashMap<String, Double>) entry1.getValue();set2 = map.entrySet();iterator2 = set2.iterator();while (iterator2.hasNext()) {entry2 = (Map.Entry) iterator2.next();ds.setValue(Double.parseDouble(entry2.getValue().toString()), entry2.getKey().toString(), entry1.getKey().toString());}}//创建折线图,折线图分水平显示和垂直显示两种// //2D折线图JFreeChart chart = ChartFactory.createLineChart(title, type, unit, ds, PlotOrientation.VERTICAL, true, true, true);// //3D折线图JFreeChart chart2 = ChartFactory.createLineChart3D(title, type, unit, ds, PlotOrientation.VERTICAL, true, true, false);//设置整个图片的标题字体chart.getTitle().setFont(font);//设置提示条字体font = new Font("宋体", Font.BOLD, 15);chart.getLegend().setItemFont(font);//得到绘图区CategoryPlot plot = (CategoryPlot) chart.getPlot();//得到绘图区的域轴(横轴),设置标签的字体plot.getDomainAxis().setLabelFont(font);// 设置背景透明度plot.setBackgroundAlpha(0.1f);// 设置网格横线颜色plot.setRangeGridlinePaint(Color.gray);// 设置网格横线大小plot.setDomainGridlineStroke(new BasicStroke(0.2F));plot.setRangeGridlineStroke(new BasicStroke(0.2F));//设置横轴标签项字体plot.getDomainAxis().setTickLabelFont(font);// 生成折线图上的数字//绘图区域(红色矩形框的部分)LineAndShapeRenderer lineAndShapeRenderer=(LineAndShapeRenderer)plot.getRenderer();lineAndShapeRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());//设置图表上的数字可见lineAndShapeRenderer.setBaseItemLabelsVisible(true);//设置图表上的数字字体lineAndShapeRenderer.setBaseItemLabelFont(new Font("宋体",Font.BOLD,15));//设置折线图拐角上的正方形//创建一个正方形Rectangle  shape=new Rectangle(4,4);lineAndShapeRenderer.setSeriesShape(0, shape);//设置拐角上图形可见lineAndShapeRenderer.setSeriesShapesVisible(0, true);/*// 获取显示线条的对象LineAndShapeRenderer lasp = (LineAndShapeRenderer) plot.getRenderer();// 设置拐点是否可见/是否显示拐点lasp.setBaseShapesVisible(true);// 设置拐点不同用不同的形状lasp.setDrawOutlines(true);// 设置线条是否被显示填充颜色lasp.setUseFillPaint(true);// 设置拐点颜色lasp.setBaseFillPaint(Color.blue);//蓝色*///设置范围轴(纵轴)字体font = new Font("宋体", Font.BOLD, 18);plot.getRangeAxis().setLabelFont(font);
//            plot.setForegroundAlpha(1.0f);return chart;} catch (Exception e) {e.printStackTrace();return null;}}/*** 生成折线图 多条* @return*/public static JFreeChart createManyLineChart(DefaultCategoryDataset dataSet){//如果把createLineChart改为createLineChart3D就变为了3D效果的折线图JFreeChart  chart = ChartFactory.createLineChart("图表标题", "X轴标题", "Y轴标题", dataSet,PlotOrientation.VERTICAL, // 绘制方向true, // 显示图例true, // 采用标准生成器false // 是否生成超链接);//如 果不使用Font,中文将显示不出来Font font = new Font("新宋体", Font.BOLD, 15);chart.getTitle().setFont(font); // 设置标题字体chart.getLegend().setItemFont(font);// 设置图例类别字体// chart.setBackgroundPaint();// 设置背景色//获取绘图区对象CategoryPlot plot = chart.getCategoryPlot();plot.setBackgroundPaint(Color.LIGHT_GRAY); // 设置绘图区背景色plot.setRangeGridlinePaint(Color.gray); // 设置水平方向背景线颜色// 设置背景透明度plot.setBackgroundAlpha(0.1f);// 设置网格横线颜色plot.setRangeGridlinePaint(Color.gray);// 设置网格横线大小plot.setDomainGridlineStroke(new BasicStroke(0.2F));plot.setRangeGridlineStroke(new BasicStroke(0.2F));plot.setRangeGridlinesVisible(true);// 设置是否显示水平方向背景线,默认值为trueplot.setDomainGridlinePaint(Color.WHITE); // 设置垂直方向背景线颜色plot.setDomainGridlinesVisible(true); // 设置是否显示垂直方向背景线,默认值为falseCategoryAxis domainAxis = plot.getDomainAxis();domainAxis.setLabelFont(font); // 设置横轴字体domainAxis.setTickLabelFont(font);// 设置坐标轴标尺值字体domainAxis.setLowerMargin(0.01);// 左边距 边框距离domainAxis.setUpperMargin(0.06);// 右边距 边框距离,防止最后边的一个数据靠近了坐标轴。domainAxis.setMaximumCategoryLabelLines(2);ValueAxis rangeAxis = plot.getRangeAxis();rangeAxis.setLabelFont(font);rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());//Y轴显示整数rangeAxis.setAutoRangeMinimumSize(1);   //最小跨度rangeAxis.setUpperMargin(0.18);//上边距,防止最大的一个数据靠近了坐标轴。rangeAxis.setLowerBound(0);   //最小值显示0rangeAxis.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);for (int i = 0; i < dataSet.getRowCount(); i++) {if (i % 2 == 0) {renderer.setSeriesStroke(i, realLine); // 利用实线绘制} else {renderer.setSeriesStroke(i, brokenLine); // 利用虚线绘制}// 生成折线图上的数字//绘图区域(红色矩形框的部分)renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());//设置图表上的数字可见renderer.setBaseItemLabelsVisible(true);//设置图表上的数字字体renderer.setBaseItemLabelFont(new Font("宋体",Font.BOLD,15));//设置折线图拐角上的正方形//创建一个正方形Rectangle  shape=new Rectangle(4,4);renderer.setSeriesShape(0, shape);//设置拐角上图形可见renderer.setSeriesShapesVisible(0, true);}plot.setNoDataMessage("无对应的数据,请重新查询。");plot.setNoDataMessageFont(font);//字体的大小plot.setNoDataMessagePaint(Color.RED);//字体颜色return chart;}/*** 生成柱状图* @param title* @param data* @param type* @param danwei* @param font* @return*/public static JFreeChart createBarChart(String title,Map<String,Map<String,Double>> data,String type,String danwei,Font font){try {//种类数据集DefaultCategoryDataset ds = new DefaultCategoryDataset();//获取迭代器:Set<Map.Entry<String, Map<String, Double>>> set1 =  data.entrySet();Iterator iterator1= set1.iterator();Iterator iterator2;HashMap<String, Double> map;Set<Map.Entry<String,Double>> set2;Map.Entry entry1;Map.Entry entry2;while(iterator1.hasNext()){entry1=(Map.Entry) iterator1.next();map=(HashMap<String, Double>) entry1.getValue();set2=map.entrySet();iterator2=set2.iterator();while (iterator2.hasNext()) {entry2= (Map.Entry) iterator2.next();ds.setValue(Double.parseDouble(entry2.getValue().toString()), entry2.getKey().toString(), entry1.getKey().toString());}}//创建柱状图,柱状图分水平显示和垂直显示两种JFreeChart chart = ChartFactory.createBarChart(title, type, danwei, ds, PlotOrientation.VERTICAL, true, true, true);//设置整个图片的标题字体chart.getTitle().setFont(font);//设置提示条字体font = new Font("宋体", Font.BOLD, 15);chart.getLegend().setItemFont(font);//得到绘图区CategoryPlot plot = (CategoryPlot) chart.getPlot();//得到绘图区的域轴(横轴),设置标签的字体plot.getDomainAxis().setLabelFont(font);//获取X轴的对象// CategoryAxis categoryAxis = plot.getDomainAxis();// 设置X轴文本倾斜45度// categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);// 设置背景透明度plot.setBackgroundAlpha(0.1f);// 设置网格横线颜色plot.setRangeGridlinePaint(Color.gray);// 设置网格横线大小plot.setDomainGridlineStroke(new BasicStroke(0.2F));plot.setRangeGridlineStroke(new BasicStroke(0.2F));//设置横轴标签项字体plot.getDomainAxis().setTickLabelFont(font);// 设置柱状图柱子相关CategoryPlot categoryPlot = chart.getCategoryPlot();BarRenderer rendererBar = (BarRenderer) categoryPlot.getRenderer();// 柱子宽度rendererBar.setMaximumBarWidth(0.05);// 柱状图颜色rendererBar.setSeriesPaint(0, Color.decode("#005AB5"));// 设置柱子上显示值rendererBar.setBaseItemLabelsVisible(true);rendererBar.setSeriesItemLabelFont(0,font);//设置范围轴(纵轴)字体plot.getRangeAxis().setLabelFont(font);plot.setForegroundAlpha(1.0f);return chart;} catch (Exception e) {e.printStackTrace();return null;}}/*** 生成3D柱状图*/public static void bar3D() {/* final String fait = "菲亚特";final String audi = "奥迪";final String ford = "福特";final String speed = "速度";final String popular = "喜欢程度";final String mailage = "邮寄";final String userrating = "用户评价";final String safty = "安全性";final DefaultCategoryDataset dataset = new DefaultCategoryDataset( );dataset.addValue( 1.0 , fait , speed );dataset.addValue( 4.0 , fait , popular );dataset.addValue( 3.0 , fait , userrating );dataset.addValue( 5.0 , fait , mailage );dataset.addValue( 5.0 , fait , safty );dataset.addValue( 5.0 , audi , speed );dataset.addValue( 7.0 , audi , popular );dataset.addValue( 6.0 , audi , userrating );dataset.addValue( 10.0 , audi , mailage );dataset.addValue( 4.0 , audi , safty );dataset.addValue( 4.0 , ford , speed );dataset.addValue( 3.0 , ford , popular );dataset.addValue( 2.0 , ford , userrating );dataset.addValue( 3.0 , ford , mailage );dataset.addValue( 6.0 , ford , safty );*/// 行关键字String seriesArray[] = {"菲亚特","奥迪","福特"};// 列关键字String categoryArray[] = {"速度","喜欢程度","邮寄","用户评价","安全性","使用性"};// 对应的值int value[] = {310,489,512,589,359,402,501,200,308,580,418,315,480,381,264,185,209,302};// 创建分类数据集DefaultCategoryDataset dataset = new DefaultCategoryDataset();int data = 0;for (int i=0;i<3;i++) {for (int j = 0; j < 6; j++) {dataset.addValue(value[data], seriesArray[i], categoryArray[j]);data++;}}// 设置字体,去除中文乱码StandardChartTheme sct = new StandardChartTheme("CN");sct.setExtraLargeFont(new Font("宋体", Font.LAYOUT_LEFT_TO_RIGHT, 15));sct.setRegularFont(new Font("宋体", Font.LAYOUT_LEFT_TO_RIGHT, 15));sct.setLargeFont(new Font("宋体", Font.LAYOUT_LEFT_TO_RIGHT, 15));ChartFactory.setChartTheme(sct);JFreeChart chart = ChartFactory.createBarChart3D("汽车使用统计","",// 类别"", // 值dataset,PlotOrientation.VERTICAL,true, true, false);//得到绘图区CategoryPlot plot = (CategoryPlot) chart.getPlot();/*//获取X轴的对象// CategoryAxis categoryAxis = plot.getDomainAxis();// 设置X轴文本倾斜45度// categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);// 设置背景透明度plot.setBackgroundAlpha(0.1f);// 设置网格横线颜色plot.setRangeGridlinePaint(Color.gray);*/ // 注释的代码放开就是背景透明/* // 注释的是设置显示数值BarRenderer renderer = new BarRenderer();renderer.setBarPainter(new StandardBarPainter());// 取消渐变效果renderer.setShadowVisible(false);// 关闭倒影renderer.setDrawBarOutline(false); // 设置柱子边框可见renderer.setItemMargin(0.03); // 组内柱子间隔为组宽的10%renderer.setMaximumBarWidth(0.03);// 设置条形柱最大宽度renderer.setMinimumBarLength(0.03);// 设置条形柱最小宽度renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());// 数据标签格式renderer.setBaseItemLabelsVisible(true);// 是否显示数据标签renderer.setSeriesPaint(0, Color.BLUE);plot.setRenderer(renderer);*/int width = 640;int height = 480;// 标注位于上侧chart.getLegend().setPosition(RectangleEdge.TOP);// 设置标注无边框chart.getLegend().setFrame(new BlockBorder(Color.WHITE));//在D盘目录下生成图片File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_3D柱状图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, width, height);} catch (IOException e) {e.printStackTrace();}}/*** 生成气泡图*/public static void bubble() {DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset( );double ad[ ] = { 30 , 40 , 50 , 60 , 70 , 80 };double ad1[ ] = { 10 , 20 , 30 , 40 , 50 , 60 };double ad2[ ] = { 4 , 5 , 10 , 8 , 9 , 6 };double ad3[ ][ ] = { ad , ad1 , ad2 };defaultxyzdataset.addSeries( "系统1" , ad3 );JFreeChart jfreechart = ChartFactory.createBubbleChart("年龄、体重和工作","重量","年龄",defaultxyzdataset,PlotOrientation.HORIZONTAL,true, true, false);XYPlot xyplot = ( XYPlot )jfreechart.getPlot();xyplot.setForegroundAlpha( 0.65F );XYItemRenderer xyitemrenderer = xyplot.getRenderer( );xyitemrenderer.setSeriesPaint( 0 , Color.blue );NumberAxis numberaxis = ( NumberAxis )xyplot.getDomainAxis( );numberaxis.setLowerMargin( 0.2 );numberaxis.setUpperMargin( 0.5 );NumberAxis numberAxis = ( NumberAxis )xyplot.getRangeAxis( );numberAxis.setLowerMargin( 0.8 );numberAxis.setUpperMargin( 0.9 );/*// 设置背景透明度xyplot.setBackgroundAlpha(0.1f);// 设置网格横线颜色xyplot.setRangeGridlinePaint(Color.gray);*/ // 注释的代码是设置背景透明度int width = 560;int height = 370;//在D盘目录下生成图片File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_气泡图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, jfreechart, width, height);} catch (IOException e) {e.printStackTrace();}}/*** 生成时序图*/public static void sequenceDiagram(){final TimeSeries series = new TimeSeries( "Random Data" );Second current = new Second();double value = 100.0;for ( int i = 0 ; i < 4000 ; i++ ){try {value = value + Math.random( ) - 0.5;series.add( current , new Double( value ) );current = ( Second ) current.next( );} catch ( SeriesException e ) {System.err.println( "Error adding to series" );}}final XYDataset dataset=( XYDataset )new TimeSeriesCollection(series);JFreeChart timeChart = ChartFactory.createTimeSeriesChart("计算测试","秒数","值",dataset,false,false,false);/*XYPlot xyplot = ( XYPlot )timeChart.getPlot( );// 设置背景透明度xyplot.setBackgroundAlpha(0.1f);// 设置网格横线颜色xyplot.setRangeGridlinePaint(Color.gray);*/ // 注释的代码是设置背景透明度int width = 560;int height = 370;//在D盘目录下生成图片File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_时序图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, timeChart, width, height);} catch (IOException e) {e.printStackTrace();}}/*** 生成曲线图*/public static void curve(){//如 果不使用Font,中文将显示不出来Font font = new Font("宋体", Font.BOLD, 25);// 数据XYSeries series = new XYSeries("2020年");series.add(01, 3542);series.add(02, 3692);series.add(03, 8542);series.add(04, 5742);XYSeries series1 = new XYSeries("2021年");series1.add(01, 1242);series1.add(02, 2612);series1.add(03, 1942);series1.add(04, 4612);XYSeriesCollection xySeriesCollection = new XYSeriesCollection();xySeriesCollection.addSeries(series);xySeriesCollection.addSeries(series1);StandardChartTheme standardChartTheme = new StandardChartTheme("CN"); // 创建主题样式standardChartTheme.setExtraLargeFont(font); // 设置标题字体standardChartTheme.setRegularFont(font); // 设置图例的字体standardChartTheme.setLargeFont(font); // 设置轴向的字体standardChartTheme.setChartBackgroundPaint(Color.WHITE);// 设置主题背景色ChartFactory.setChartTheme(standardChartTheme);// 应用主题样式// 定义图表对象 图表的标题-饼形图的数据集对象-是否显示图列-是否显示提示文-是否生成超链接JFreeChart chart = ChartFactory.createXYLineChart("年度绩效", "季度", "销售额", xySeriesCollection,PlotOrientation.VERTICAL, true, true, false);// chart.setTitle(new TextTitle(title[0], new Font("宋书", Font.BOLD, 64)));// 重新设置标题// chart.removeLegend();// 是否移除图例XYPlot plot = (XYPlot)chart.getPlot(); // 获得图表显示对象plot.setOutlineVisible(false);// 是否显示外边框plot.setOutlinePaint(Color.WHITE);// 外边框颜色// plot.setOutlineStroke(new BasicStroke(2.f));// 外边框框线粗细plot.setBackgroundPaint(Color.WHITE);// 白色背景plot.setNoDataMessage("无图表数据");// 无数据提示plot.setNoDataMessageFont(font);// 提示字体plot.setNoDataMessagePaint(Color.RED);// 提示字体颜色// 图例LegendTitle legend = chart.getLegend();// 图例对象legend.setPosition(RectangleEdge.BOTTOM);// 图例位置 上、下、左、右legend.setVisible(true);// 是否显示图例legend.setBorder(BlockBorder.NONE);// 图例无边框legend.setItemFont(font);// 图例大小// 网格线plot.setDomainGridlinePaint(Color.BLUE);plot.setDomainGridlinesVisible(true);// 竖线plot.setRangeGridlinePaint(Color.BLACK);plot.setRangeGridlinesVisible(true);// 横线// 横坐标NumberAxis xAxis = (NumberAxis)plot.getDomainAxis();// 获得横坐标xAxis.setTickLabelFont(font);// 设置X轴字体xAxis.setLabelFont(font);// 轴标签值字体xAxis.setTickLabelFont(font);// 轴标签字体xAxis.setAxisLineStroke(new BasicStroke(2f)); // 设置轴线粗细xAxis.setAxisLinePaint(Color.BLACK);// 轴线颜色xAxis.setLowerMargin(0.03D);// 左侧边距xAxis.setUpperMargin(0.03D);// 右侧边距xAxis.setTickUnit(new NumberTickUnit(1D));// 间距1D// 纵坐标ValueAxis yAxis = plot.getRangeAxis();yAxis.setTickLabelFont(font);// 设置y轴字体yAxis.setLabelFont(font);// 设置X轴标签字体yAxis.setAxisLineStroke(new BasicStroke(1f)); // 设置y轴线粗细yAxis.setAxisLinePaint(Color.BLACK);// 轴线颜色yAxis.setUpperMargin(0.18D);// 上边距yAxis.setLowerMargin(0.1D);// 下边距// 标签XYSplineRenderer renderer = new XYSplineRenderer();renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator());renderer.setBaseItemLabelsVisible(true); // 基本项标签显示renderer.setBaseShapesVisible(true);renderer.setShapesFilled(Boolean.TRUE); // 在数据点显示实心的小图标renderer.setShapesVisible(true); // 设置显示小图标renderer.setItemLabelFont(font);// 设置数字的字体大小renderer.setStroke(new BasicStroke(4f));plot.setRenderer(renderer);//在D盘目录下生成图片int width = 1800;int height = 800;File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_曲线图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, width, height);} catch (IOException e) {e.printStackTrace();}}/*** 生成环形图*/public static void annular(){DefaultPieDataset dataSet = new DefaultPieDataset();int i, j;String[] key = { "私募股权","房地产","基金","现金宝宝","股票" };int[] value = { 150, 20, 325, 78, 105 };for (i = 0, j = 0; i < key.length && j < value.length; i++, j++) {dataSet.setValue(key[i], value[j]);}JFreeChart chart = ChartFactory.createRingChart("2021年收入", dataSet, true, false, false);// 设置显示标注chart.getLegend().setVisible(true);Font font = new Font("宋体", Font.BOLD, 15);chart.getLegend().setItemFont(font);// 标注位于上侧// chart.getLegend().setPosition(RectangleEdge.TOP);// 设置标注无边框chart.getLegend().setFrame(new BlockBorder(Color.WHITE));// 环形图RingPlot ringplot = (RingPlot) chart.getPlot();ringplot.setOutlineVisible(false);//{2}表示显示百分比  //{0}:key {1}:value {2}:百分比 {3}:sumringplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}:{1}"));ringplot.setBackgroundPaint(new Color(253,253,253));ringplot.setOutlineVisible(false);/*//设置标签样式ringplot.setLabelFont(new Font("宋体", Font.BOLD, 15));ringplot.setSimpleLabels(true);ringplot.setLabelLinkPaint(Color.WHITE);ringplot.setLabelOutlinePaint(Color.WHITE);ringplot.setLabelLinksVisible(false);ringplot.setLabelShadowPaint(null);ringplot.setLabelOutlinePaint(new Color(0,true));ringplot.setLabelBackgroundPaint(new Color(0,true));ringplot.setLabelPaint(Color.WHITE);*/ringplot.setSectionOutlinePaint(Color.WHITE);ringplot.setSeparatorsVisible(true);ringplot.setSeparatorPaint(Color.WHITE);ringplot.setShadowPaint(new Color(253,253,253));// 设置深度,即带颜⾊圆环的宽度ringplot.setSectionDepth(0.4);ringplot.setStartAngle(90);// 指定颜色ringplot.setDrawingSupplier(new DefaultDrawingSupplier(new Paint[] {new Color(134, 212, 222),new Color(174, 145, 195),new Color(255, 162, 195),new Color(249, 163, 86),new Color(119, 173, 195)},DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE));//在D盘目录下生成图片int width = 800;int height = 600;File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_环形图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, width, height);} catch (IOException e) {e.printStackTrace();}}/*** 生成区域图*/public static void areaChart(){// 行关键字String seriesArray[] = {"JAVA图书","Android图书","PHP图书"};// 列关键字String categoryArray[] = {"1月","2月","3月","4月","5月","6月"};// 对应的值int value[] = {310,489,512,589,359,402,501,200,308,580,418,315,480,381,264,185,209,302};// 创建分类数据集DefaultCategoryDataset dataset = new DefaultCategoryDataset();int data = 0;for (int i=0;i<3;i++) {for (int j = 0; j < 6; j++) {dataset.addValue(value[data], seriesArray[i], categoryArray[j]);data++;}}// 创建区域图对象JFreeChart chart = ChartFactory.createAreaChart("2018年上半年销售量",// 图表标题"月份", // X轴标签"销售量(单位:本)",// Y轴标签dataset,               // 数据集PlotOrientation.VERTICAL,// 图表方向为垂直方向true,             // 是否显示图例false,           // 是否生成工具false               // 是否生成URL链接);Font font = new Font("宋体", Font.BOLD, 15);// 标题TextTitle textTitle = chart.getTitle();textTitle.setFont(new Font("宋体", Font.PLAIN, 20));// 图例LegendTitle legendTitle = chart.getLegend();legendTitle.setItemFont(new Font("宋体", Font.PLAIN, 14));CategoryPlot categoryPlot = chart.getCategoryPlot();// 图表CategoryAxis categoryAxis = categoryPlot.getDomainAxis();categoryAxis.setTickLabelFont(font); // X轴字体categoryAxis.setLabelFont(font);     // X轴标签字体ValueAxis valueAxis = categoryPlot.getRangeAxis();                // Y轴对象valueAxis.setTickLabelFont(font);    // Y轴字体valueAxis.setLabelFont(font);        // Y轴标签字体categoryPlot.setForegroundAlpha(0.5f);//得到绘图区CategoryPlot plot = (CategoryPlot) chart.getPlot();//得到绘图区的域轴(横轴),设置标签的字体plot.getDomainAxis().setLabelFont(font);// 设置背景透明度plot.setBackgroundAlpha(0.1f);// 设置网格横线颜色plot.setRangeGridlinePaint(Color.gray);// 设置网格横线大小plot.setDomainGridlineStroke(new BasicStroke(0.2F));plot.setRangeGridlineStroke(new BasicStroke(0.2F));chart.getLegend().setItemFont(font);// 标注位于上侧// chart.getLegend().setPosition(RectangleEdge.TOP);// 设置标注无边框chart.getLegend().setFrame(new BlockBorder(Color.WHITE));//在D盘目录下生成图片int width = 800;int height = 600;File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_区域图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, width, height);} catch (IOException e) {e.printStackTrace();}}/*** 生成气泡图2*/public static void bubble2(){// 系列关键字String seriesArray[] = {"JAVA图书","Android图书","PHP图书"};// 创建分类数据集DefaultXYZDataset dataset = new DefaultXYZDataset();double data1[][] = new double[][] { { 600 }, { 10 }, { 600 / (10 * 10) } };double data2[][] = new double[][] { { 650 }, { 10 }, { 650 / (10 * 10) } };double data3[][] = new double[][] { { 800 }, { 16 }, { 800 / (16 * 10) } };for (int i=0;i<seriesArray.length;i++) {dataset.addSeries(seriesArray[i], i == 0 ? data1: i==1 ? data2:data3);}JFreeChart chart = ChartFactory.createBubbleChart("2018年上半年销售量",    // 图表标题"页数",                  // X轴标签"章数",                  // Y轴标签dataset,                 // 数据集PlotOrientation.VERTICAL,// 图表方向为垂直方向true,                    // 是否显示图例false,                   // 是否生成工具false                    // 是否生成URL链接);Font font = new Font("宋体", Font.BOLD, 15);// 标题TextTitle textTitle = chart.getTitle();textTitle.setFont(new Font("宋体", Font.PLAIN, 20));LegendTitle legendTitle = chart.getLegend();// 图例legendTitle.setItemFont(new Font("宋体", Font.PLAIN, 14));XYPlot plot = chart.getXYPlot();// 获取气泡图区域对象NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();// X轴对象domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 14));NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();// Y轴对象rangeAxis.setLabelFont(new Font("宋体", Font.PLAIN, 14));plot.setForegroundAlpha(0.4f);// 设置背景透明度plot.setBackgroundAlpha(0.1f);// 设置网格横线颜色plot.setRangeGridlinePaint(Color.gray); // 注释的代码是设置背景透明度chart.getLegend().setItemFont(font);// 标注位于上侧// chart.getLegend().setPosition(RectangleEdge.TOP);// 设置标注无边框chart.getLegend().setFrame(new BlockBorder(Color.WHITE));//在D盘目录下生成图片int width = 800;int height = 600;File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_气泡图2" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, width, height);} catch (IOException e) {e.printStackTrace();}}/*** 生成分布图*/public static void chartPanel(){// 行关键字String seriesArray[] = {"JAVA图书","Android图书","PHP图书"};// 列关键字String categoryArray[] = {"1月","2月","3月","4月","5月","6月"};// 对应的值int value[] = {310,489,512,589,359,402,501,200,308,580,418,315,480,381,264,185,209,302};// 创建分类数据集DefaultCategoryDataset dataset = new DefaultCategoryDataset();int data = 0;for (int i=0;i<3;i++) {for (int j = 0; j < 6; j++) {dataset.addValue(value[data], seriesArray[i], categoryArray[j]);data++;}}CategoryItemRenderer renderer = new CategoryStepRenderer(true); // 分布图渲染对象renderer.setSeriesStroke(0, new BasicStroke(5));          // 将第一行数据线条加粗CategoryAxis domainAxis = new CategoryAxis("月份");               // 创建X轴domainAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 14));   // X轴字体domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 14));       // X轴标签字体ValueAxis rangeAxis = new NumberAxis("销售量(单位:本)");       // 创建Y轴rangeAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 14));    // Y轴字体rangeAxis.setLabelFont(new Font("宋体", Font.PLAIN, 14));        // Y轴标签字// 创建区域对象CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);JFreeChart chart = new JFreeChart("2018年上半年销售量", plot);   // 生成图表TextTitle textTitle = chart.getTitle();                           // 标题textTitle.setFont(new Font("宋体", Font.PLAIN, 20));LegendTitle legendTitle = chart.getLegend();                     // 图例legendTitle.setItemFont(new Font("宋体", Font.PLAIN, 14));Font font = new Font("宋体", Font.BOLD, 15);//得到绘图区的域轴(横轴),设置标签的字体plot.getDomainAxis().setLabelFont(font);// 设置背景透明度plot.setBackgroundAlpha(0.1f);// 设置网格横线颜色plot.setRangeGridlinePaint(Color.gray);// 设置网格横线大小plot.setDomainGridlineStroke(new BasicStroke(0.2F));plot.setRangeGridlineStroke(new BasicStroke(0.2F));chart.getLegend().setItemFont(font);// 标注位于上侧// chart.getLegend().setPosition(RectangleEdge.TOP);// 设置标注无边框chart.getLegend().setFrame(new BlockBorder(Color.WHITE));//在D盘目录下生成图片int width = 800;int height = 600;File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_分布图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, width, height);} catch (IOException e) {e.printStackTrace();}}/*** 联合分类图 折线、柱状*/public static void chartPanel1(){// 行关键字String seriesArray[] = {"JAVA图书","Android图书","PHP图书"};// 列关键字String categoryArray[] = {"1月","2月","3月","4月","5月","6月"};// 对应的值int value[] = {310,489,512,589,359,402,501,200,308,580,418,315,480,381,264,185,209,302};// 创建分类数据集DefaultCategoryDataset dataset = new DefaultCategoryDataset();int data = 0;for (int i=0;i<3;i++) {for (int j = 0; j < 6; j++) {dataset.addValue(value[data], seriesArray[i], categoryArray[j]);data++;}}LineAndShapeRenderer renderer1 = new LineAndShapeRenderer(); // 生成线形图渲染BarRenderer renderer2 = new BarRenderer();                     // 生成柱形图渲染// 区域图渲染AreaRenderer renderer3 = new AreaRenderer();CategoryAxis domainAxis = new CategoryAxis("月份");            // 设置X轴NumberAxis rangeAxis = new NumberAxis("销售量(单位:本)");   // 设置Y轴//设置Y轴 字体和颜色rangeAxis.setLabelFont(new Font("黑体",Font.PLAIN,12));rangeAxis.setLabelPaint(Color.BLUE) ; // 字体颜色rangeAxis.setTickLabelFont(new Font("黑体",Font.PLAIN,12));// 使用同样的数据,创建不同图表区域对象CategoryPlot plot1 = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer1);CategoryPlot plot2 = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer2);CategoryPlot plot3 = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer3);// 生成折线图上的数字//绘图区域(红色矩形框的部分)/*LineAndShapeRenderer lineAndShapeRenderer=(LineAndShapeRenderer)plot1.getRenderer();lineAndShapeRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());//设置图表上的数字可见lineAndShapeRenderer.setBaseItemLabelsVisible(true);//设置图表上的数字字体lineAndShapeRenderer.setBaseItemLabelFont(new Font("宋体",Font.BOLD,15));*/// 设置联合分类图表CombinedDomainCategoryPlot plot = new CombinedDomainCategoryPlot(domainAxis);plot.add(plot1);                                                  // 添加图表区域对象plot.add(plot2);// plot.add(plot3);JFreeChart chart = new JFreeChart("2018年上半年销售量", plot); // 创建图表TextTitle textTitle = chart.getTitle();                          // 标题textTitle.setFont(new Font("宋体", Font.PLAIN, 20));// 图例LegendTitle legendTitle = chart.getLegend();legendTitle.setItemFont(new Font("宋体", Font.PLAIN, 14));// 图表区域CategoryPlot categoryPlot = chart.getCategoryPlot();// X轴CategoryAxis categoryAxis = categoryPlot.getDomainAxis();// X轴字体categoryAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 14));// X轴标签字体categoryAxis.setLabelFont(new Font("宋体", Font.PLAIN, 14));// 标注位于上侧// chart.getLegend().setPosition(RectangleEdge.TOP);// 设置标注无边框chart.getLegend().setFrame(new BlockBorder(Color.WHITE));//在D盘目录下生成图片int width = 800;int height = 600;File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_联合分类图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, width, height);} catch (IOException e) {e.printStackTrace();}}/*** 双轴图*/public static void biaxial(){// 行关键字String seriesArray[] = {"JAVA图书","Android图书","PHP图书"};// 列关键字String categoryArray[] = {"1月","2月","3月","4月","5月","6月"};// 对应的值int value[] = {310,489,512,589,359,402,501,200,308,580,418,315,480,381,264,185,209,302};String lineArray[] = {"C++图书","C#图书","GO图书"};// 创建分类数据集-柱状图数据DefaultCategoryDataset columnarDataset = new DefaultCategoryDataset();int data = 0;for (int i=0;i<seriesArray.length;i++) {for (int j = 0; j < 6; j++) {columnarDataset.addValue(value[data], seriesArray[i], categoryArray[j]);data++;}}// 创建分类数据集-折线图DefaultCategoryDataset lineDataset = new DefaultCategoryDataset();data = 0;for (int i=0;i<lineArray.length;i++) {for (int k = 0; k < 6; k++) {lineDataset.addValue(value[data], lineArray[i], categoryArray[k]);data++;}}// 创建柱状图对象JFreeChart chart = ChartFactory.createBarChart("2018年上半年销售量",                           // 图表标题"月份",                                          // x轴标签"销售量(单位:本)",                            // y轴标签columnarDataset,                                        // 数据集PlotOrientation.VERTICAL,                     // 图表方向为垂直方向true,                                           // 是否显示图例false,                                          // 是否生成工具false                                           // 是否生成URL链接);// 标题TextTitle textTitle = chart.getTitle();textTitle.setFont(new Font("宋体", Font.PLAIN, 20));// 图例LegendTitle legendTitle = chart.getLegend();legendTitle.setItemFont(new Font("宋体", Font.PLAIN, 14));// 图表区域对象CategoryPlot categoryPlot = chart.getCategoryPlot();// X轴对象CategoryAxis categoryAxis = categoryPlot.getDomainAxis();// X轴字体categoryAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 14));// X轴标签字体categoryAxis.setLabelFont(new Font("宋体", Font.PLAIN, 14));// y轴ValueAxis valueAxis = categoryPlot.getRangeAxis();// y轴字体valueAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 14));// y轴标签字体valueAxis.setLabelFont(new Font("宋体", Font.PLAIN, 14));// 读取图表数据2categoryPlot.setDataset(1, lineDataset);// 获取线性渲染对象LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();// 设置线形图categoryPlot.setRenderer(1, renderer2);// 设置双Y轴ValueAxis axis2 = new NumberAxis("网购销售量");// 设置Y轴最大值axis2.setUpperBound(200);categoryPlot.setRangeAxis(1, axis2);// 标注位于上侧// chart.getLegend().setPosition(RectangleEdge.TOP);// 设置标注无边框chart.getLegend().setFrame(new BlockBorder(Color.WHITE));// 设置背景透明度categoryPlot.setBackgroundAlpha(0.1f);// 设置网格横线颜色categoryPlot.setRangeGridlinePaint(Color.gray);// 设置网格横线大小categoryPlot.setDomainGridlineStroke(new BasicStroke(0.2F));categoryPlot.setRangeGridlineStroke(new BasicStroke(0.2F));//在D盘目录下生成图片int width = 800;int height = 600;File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_双轴图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, width, height);} catch (IOException e) {e.printStackTrace();}}/*** 生成甘特图*/public static void createGanttChart(){IntervalCategoryDataset dataset = createSampleDataset();JFreeChart chart = ChartFactory.createGanttChart("任务管理系统","任务各阶段详细实施计划","任务周期",dataset,true,false,false);CategoryPlot plot=chart.getCategoryPlot();chart.getTitle().setFont(new Font("宋体",Font.BOLD,20));CategoryAxis domainAxis=plot.getDomainAxis();//水平底部列表domainAxis.setLabelFont(new Font("宋体",Font.BOLD,15));//水平底部标题domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,15));//垂直标题ValueAxis rangeAxis = plot.getRangeAxis();rangeAxis.setLabelFont(new Font("宋体",Font.BOLD,16));//用来控制时间轴的显示,防止乱码DateAxis da = (DateAxis)plot.getRangeAxis(0);da.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));//设置提示条字体/*Font font = new Font("宋体", Font.BOLD, 15);chart.getLegend().setItemFont(font);// 标注位于上侧// chart.getLegend().setPosition(RectangleEdge.TOP);*/// 设置标注无边框chart.getLegend().setFrame(new BlockBorder(Color.WHITE));Font font = new Font("宋体", Font.BOLD, 15);//得到绘图区的域轴(横轴),设置标签的字体// plot.getDomainAxis().setLabelFont(font);// 设置背景透明度plot.setBackgroundAlpha(0.1f);// 设置网格横线颜色plot.setRangeGridlinePaint(Color.gray);// 设置网格横线大小plot.setDomainGridlineStroke(new BasicStroke(0.2F));plot.setRangeGridlineStroke(new BasicStroke(0.2F));//在D盘目录下生成图片int width = 800;int height = 600;File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_甘特图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, width, height,null);} catch (IOException e) {e.printStackTrace();}}/*** 生成K线图*/public static void kImage(){SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式double highValue = Double.MIN_VALUE;// 设置K线数据当中的最大值double minValue = Double.MAX_VALUE;// 设置K线数据当中的最小值double high2Value = Double.MIN_VALUE;// 设置成交量的最大值double min2Value = Double.MAX_VALUE;// 设置成交量的最低值OHLCSeries series = new OHLCSeries("");// 高开低收数据序列,股票K线图的四个数据,依次是开,高,低,收series.add(new Day(28, 9, 2007), 9.2, 9.58, 9.16, 9.34);series.add(new Day(27, 9, 2007), 8.9, 9.06, 8.83, 8.96);series.add(new Day(26, 9, 2007), 9.0, 9.1, 8.82, 9.04);series.add(new Day(25, 9, 2007), 9.25, 9.33, 8.88, 9.00);series.add(new Day(24, 9, 2007), 9.05, 9.50, 8.91, 9.25);series.add(new Day(21, 9, 2007), 8.68, 9.05, 8.40, 9.00);series.add(new Day(20, 9, 2007), 8.68, 8.95, 8.50, 8.69);series.add(new Day(19, 9, 2007), 8.80, 8.94, 8.50, 8.66);series.add(new Day(18, 9, 2007), 8.88, 9.17, 8.69, 8.80);series.add(new Day(17, 9, 2007), 8.26, 8.98, 8.15, 8.89);series.add(new Day(14, 9, 2007), 8.44, 8.45, 8.13, 8.33);series.add(new Day(13, 9, 2007), 8.13, 8.46, 7.97, 8.42);series.add(new Day(12, 9, 2007), 8.2, 8.4, 7.81, 8.13);series.add(new Day(11, 9, 2007), 9.0, 9.0, 8.1, 8.24);series.add(new Day(10, 9, 2007), 8.6, 9.03, 8.40, 8.95);series.add(new Day(7, 9, 2007), 8.89, 9.04, 8.70, 8.73);series.add(new Day(6, 9, 2007), 8.4, 9.08, 8.33, 8.88);series.add(new Day(5, 9, 2007), 8.2, 8.74, 8.17, 8.36);series.add(new Day(4, 9, 2007), 7.7, 8.46, 7.67, 8.27);series.add(new Day(3, 9, 2007), 7.5, 7.8, 7.48, 7.69);series.add(new Day(31, 8, 2007), 7.4, 7.6, 7.28, 7.43);series.add(new Day(30, 8, 2007), 7.42, 7.56, 7.31, 7.40);series.add(new Day(29, 8, 2007), 7.42, 7.66, 7.22, 7.33);series.add(new Day(28, 8, 2007), 7.31, 7.70, 7.15, 7.56);series.add(new Day(27, 8, 2007), 7.05, 7.46, 7.02, 7.41);series.add(new Day(24, 8, 2007), 7.05, 7.09, 6.90, 6.99);series.add(new Day(23, 8, 2007), 7.12, 7.16, 7.00, 7.03);series.add(new Day(22, 8, 2007), 6.96, 7.15, 6.93, 7.11);series.add(new Day(21, 8, 2007), 7.10, 7.15, 7.02, 7.07);series.add(new Day(20, 8, 2007), 7.02, 7.19, 6.94, 7.14);final OHLCSeriesCollection seriesCollection = new OHLCSeriesCollection();// 保留K线数据的数据集,必须申明为final,后面要在匿名内部类里面用到seriesCollection.addSeries(series);TimeSeries series2=new TimeSeries("");// 对应时间成交量数据series2.add(new Day(28, 9, 2007), 260659400/100);series2.add(new Day(27, 9, 2007), 119701900/100);series2.add(new Day(26, 9, 2007), 109719000/100);series2.add(new Day(25, 9, 2007), 178492400/100);series2.add(new Day(24, 9, 2007), 269978500/100);series2.add(new Day(21, 9, 2007), 361042300/100);series2.add(new Day(20, 9, 2007), 173912600/100);series2.add(new Day(19, 9, 2007), 154622600/100);series2.add(new Day(18, 9, 2007), 200661600/100);series2.add(new Day(17, 9, 2007), 312799600/100);series2.add(new Day(14, 9, 2007), 141652900/100);series2.add(new Day(13, 9, 2007), 221260400/100);series2.add(new Day(12, 9, 2007), 274795400/100);series2.add(new Day(11, 9, 2007), 289287300/100);series2.add(new Day(10, 9, 2007), 289063600/100);series2.add(new Day(7, 9, 2007), 351575300/100);series2.add(new Day(6, 9, 2007), 451357300/100);series2.add(new Day(5, 9, 2007), 442421200/100);series2.add(new Day(4, 9, 2007), 671942600/100);series2.add(new Day(3, 9, 2007), 349647800/100);series2.add(new Day(31, 8, 2007), 225339300/100);series2.add(new Day(30, 8, 2007), 160048200/100);series2.add(new Day(29, 8, 2007), 247341700/100);series2.add(new Day(28, 8, 2007), 394975400/100);series2.add(new Day(27, 8, 2007), 475797500/100);series2.add(new Day(24, 8, 2007), 297679500/100);series2.add(new Day(23, 8, 2007), 191760600/100);series2.add(new Day(22, 8, 2007), 232570200/100);series2.add(new Day(21, 8, 2007), 215693200/100);series2.add(new Day(20, 8, 2007), 200287500/100);TimeSeriesCollection timeSeriesCollection=new TimeSeriesCollection();// 保留成交量数据的集合timeSeriesCollection.addSeries(series2);// 获取K线数据的最高值和最低值int seriesCount = seriesCollection.getSeriesCount();// 一共有多少个序列,目前为一个for (int i = 0; i < seriesCount; i++) {int itemCount = seriesCollection.getItemCount(i);// 每一个序列有多少个数据项for (int j = 0; j < itemCount; j++) {if (highValue < seriesCollection.getHighValue(i, j)) {// 取第i个序列中的第j个数据项的最大值highValue = seriesCollection.getHighValue(i, j);}if (minValue > seriesCollection.getLowValue(i, j)) {// 取第i个序列中的第j个数据项的最小值minValue = seriesCollection.getLowValue(i, j);}}}// 获取最高值和最低值int seriesCount2 = timeSeriesCollection.getSeriesCount();// 一共有多少个序列,目前为一个for (int i = 0; i < seriesCount2; i++) {int itemCount = timeSeriesCollection.getItemCount(i);// 每一个序列有多少个数据项for (int j = 0; j < itemCount; j++) {if (high2Value < timeSeriesCollection.getYValue(i,j)) {// 取第i个序列中的第j个数据项的值high2Value = timeSeriesCollection.getYValue(i,j);}if (min2Value > timeSeriesCollection.getYValue(i, j)) {// 取第i个序列中的第j个数据项的值min2Value = timeSeriesCollection.getYValue(i, j);}}}final CandlestickRenderer candlestickRender=new CandlestickRenderer();// 设置K线图的画图器,必须申明为final,后面要在匿名内部类里面用到candlestickRender.setUseOutlinePaint(true); // 设置是否使用自定义的边框线,程序自带的边框线的颜色不符合中国股票市场的习惯candlestickRender.setAutoWidthMethod(CandlestickRenderer.WIDTHMETHOD_AVERAGE);// 设置如何对K线图的宽度进行设定candlestickRender.setAutoWidthGap(0.001);// 设置各个K线图之间的间隔candlestickRender.setUpPaint(Color.RED);// 设置股票上涨的K线图颜色candlestickRender.setDownPaint(Color.GREEN);// 设置股票下跌的K线图颜色DateAxis x1Axis=new DateAxis();// 设置x轴,也就是时间轴x1Axis.setAutoRange(false);// 设置不采用自动设置时间范围try{x1Axis.setRange(dateFormat.parse("2007-08-20"),dateFormat.parse("2007-09-29"));// 设置时间范围,注意时间的最大值要比已有的时间最大值要多一天}catch(Exception e){e.printStackTrace();}x1Axis.setTimeline(SegmentedTimeline.newMondayThroughFridayTimeline());// 设置时间线显示的规则,用这个方法就摒除掉了周六和周日这些没有交易的日期(很多人都不知道有此方法),使图形看上去连续x1Axis.setAutoTickUnitSelection(false);// 设置不采用自动选择刻度值x1Axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);// 设置标记的位置x1Axis.setStandardTickUnits(DateAxis.createStandardDateTickUnits());// 设置标准的时间刻度单位x1Axis.setTickUnit(new DateTickUnit(DateTickUnit.DAY,7));// 设置时间刻度的间隔,一般以周为单位x1Axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));// 设置显示时间的格式NumberAxis y1Axis=new NumberAxis();// 设定y轴,就是数字轴y1Axis.setAutoRange(false);// 不不使用自动设定范围y1Axis.setRange(minValue*0.9, highValue*1.1);// 设定y轴值的范围,比最低值要低一些,比最大值要大一些,这样图形看起来会美观些y1Axis.setTickUnit(new NumberTickUnit((highValue*1.1-minValue*0.9)/10));// 设置刻度显示的密度XYPlot plot1=new XYPlot(seriesCollection,x1Axis,y1Axis,candlestickRender);// 设置画图区域对象XYBarRenderer xyBarRender=new XYBarRenderer(){private static final long serialVersionUID = 1L;// 为了避免出现警告消息,特设定此值public Paint getItemPaint(int i, int j){// 匿名内部类用来处理当日的成交量柱形图的颜色与K线图的颜色保持一致if(seriesCollection.getCloseValue(i,j)>seriesCollection.getOpenValue(i,j)){// 收盘价高于开盘价,股票上涨,选用股票上涨的颜色return candlestickRender.getUpPaint();}else{return candlestickRender.getDownPaint();}}};xyBarRender.setMargin(0.1);// 设置柱形图之间的间隔NumberAxis y2Axis=new NumberAxis();// 设置Y轴,为数值,后面的设置,参考上面的y轴设置y2Axis.setAutoRange(false);y2Axis.setRange(min2Value*0.9, high2Value*1.1);y2Axis.setTickUnit(new NumberTickUnit((high2Value*1.1-min2Value*0.9)/4));XYPlot plot2=new XYPlot(timeSeriesCollection,null,y2Axis,xyBarRender);// 建立第二个画图区域对象,主要此时的x轴设为了null值,因为要与第一个画图区域对象共享x轴CombinedDomainXYPlot combineddomainxyplot = new CombinedDomainXYPlot(x1Axis);// 建立一个恰当的联合图形区域对象,以x轴为共享轴combineddomainxyplot.add(plot1, 2);// 添加图形区域对象,后面的数字是计算这个区域对象应该占据多大的区域2/3combineddomainxyplot.add(plot2, 1);// 添加图形区域对象,后面的数字是计算这个区域对象应该占据多大的区域1/3combineddomainxyplot.setGap(10);// 设置两个图形区域对象之间的间隔空间JFreeChart chart = new JFreeChart("中国联通", JFreeChart.DEFAULT_TITLE_FONT, combineddomainxyplot, false);//在D盘目录下生成图片int width = 800;int height = 600;File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_k线图" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, width, height);} catch (IOException e) {e.printStackTrace();}//为了能够保证K线图的上影线和下影线能够和K线图本身的颜色保持一致,找了很多的方法设置都不成功,可以说目前暂不提供单独绘制K线边框颜色的方法,所以,经过本人的实验,对其中的源代码进行了下修改,具体修改的地方是在下载回来的文件目中source\org\jfree\chart\renderer\xy\CandlestickRenderer.java文件,将//Paint p = getItemPaint(series, item);//           Paint outlinePaint = null;//           outlinePaint = getItemOutlinePaint(series, item);//}////修改为如下的代码,这样就会保证K线图的上影线和下影线能够和K线图本身的颜色保持一致,符合中国股票市场K线图形颜色的习惯://Paint p = getItemPaint(series, item);//           Paint outlinePaint = null;//           if (this.useOutlinePaint) {//            if(yClose>yOpen){//             if (this.upPaint != null) {//              outlinePaint=this.upPaint;//                   }//                   else {//                    outlinePaint=p;//                   }//            }else{//             if (this.downPaint != null) {//              outlinePaint=this.downPaint;//                   }//                   else {//                    outlinePaint=p;//                   }//            }}/*** 生成柱状图-横向*/public static void bar3DHx() {// 行关键字String seriesArray[] = {"菲亚特","奥迪","福特"};// 列关键字String categoryArray[] = {"速度","喜欢程度","邮寄","用户评价","安全性","使用性"};// 对应的值int value[] = {310,489,512,589,359,402,501,200,308,580,418,315,480,381,264,185,209,302};// 创建分类数据集DefaultCategoryDataset dataset = new DefaultCategoryDataset();int data = 0;for (int i=0;i<3;i++) {for (int j = 0; j < 6; j++) {dataset.addValue(value[data], seriesArray[i], categoryArray[j]);data++;}}// 设置字体,去除中文乱码StandardChartTheme sct = new StandardChartTheme("CN");sct.setExtraLargeFont(new Font("宋体", Font.LAYOUT_LEFT_TO_RIGHT, 15));sct.setRegularFont(new Font("宋体", Font.LAYOUT_LEFT_TO_RIGHT, 15));sct.setLargeFont(new Font("宋体", Font.LAYOUT_LEFT_TO_RIGHT, 15));ChartFactory.setChartTheme(sct);JFreeChart chart = ChartFactory.createBarChart3D("汽车使用统计","",// 类别"", // 值dataset,PlotOrientation.HORIZONTAL,true, true, false);//得到绘图区CategoryPlot plot = (CategoryPlot) chart.getPlot();/*//获取X轴的对象// CategoryAxis categoryAxis = plot.getDomainAxis();// 设置X轴文本倾斜45度// categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);// 设置背景透明度plot.setBackgroundAlpha(0.1f);// 设置网格横线颜色plot.setRangeGridlinePaint(Color.gray);*/ // 注释的代码放开就是背景透明/* // 注释的是设置显示数值BarRenderer renderer = new BarRenderer();renderer.setBarPainter(new StandardBarPainter());// 取消渐变效果renderer.setShadowVisible(false);// 关闭倒影renderer.setDrawBarOutline(false); // 设置柱子边框可见renderer.setItemMargin(0.03); // 组内柱子间隔为组宽的10%renderer.setMaximumBarWidth(0.03);// 设置条形柱最大宽度renderer.setMinimumBarLength(0.03);// 设置条形柱最小宽度renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());// 数据标签格式renderer.setBaseItemLabelsVisible(true);// 是否显示数据标签renderer.setSeriesPaint(0, Color.BLUE);plot.setRenderer(renderer);*/// 取得纵轴NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis();int width = 640;int height = 480;// 标注位于上侧chart.getLegend().setPosition(RectangleEdge.TOP);// 设置标注无边框chart.getLegend().setFrame(new BlockBorder(Color.WHITE));//在D盘目录下生成图片File p = new File(imagePath);if (!p.exists()) {p.mkdirs();}String imageName = System.currentTimeMillis() + "_3D柱状图_横向" + ".jpeg";File file = new File(p.getPath() + "/" + imageName);try {if(file.exists()) {file.delete();}ChartUtilities.saveChartAsJPEG(file, chart, width, height);} catch (IOException e) {e.printStackTrace();}}private static Date date(final int day, final int month, final int year){final Calendar calendar = Calendar.getInstance();calendar.set(year, month, day);final Date result = calendar.getTime();return result;}private static IntervalCategoryDataset createSampleDataset() {final TaskSeries s1 = new TaskSeries("时间表");final Task t1 = new Task("任务1", date(1, Calendar.JANUARY, 2001), date(5, Calendar.APRIL, 2001));t1.setPercentComplete(0.8);s1.add(t1);// 创建一个任务并插入两个子任务final Task t3 = new Task("任务2", date(10, Calendar.APRIL, 2001), date(5, Calendar.MAY, 2001));final Task st31 = new Task("需求1", date(10, Calendar.APRIL, 2001), date(25, Calendar.APRIL, 2001));st31.setPercentComplete(0.50);final Task st32 = new Task("需求2", date(1, Calendar.MAY, 2001), date(5, Calendar.MAY, 2001));st32.setPercentComplete(1.0);t3.addSubtask(st31);t3.addSubtask(st32);s1.add(t3);final Task t5 = new Task("任务3", date(2, Calendar.JUNE, 2001), date(2, Calendar.JUNE, 2001));s1.add(t5);final Task t6 = new Task("任务4", date(3, Calendar.MARCH, 2001), date(31, Calendar.JULY, 2001));t6.setPercentComplete(0.60);s1.add(t6);final Task t8 = new Task("任务结束", date(10, Calendar.AUGUST, 2001), date(10, Calendar.AUGUST, 2001));t8.setPercentComplete(0.0);s1.add(t8);final Task t9 = new Task("任务试用", date(12, Calendar.AUGUST, 2001), date(12, Calendar.SEPTEMBER, 2001));t9.setPercentComplete(0.0);s1.add(t9);final Task t10 = new Task("任务测试", date(13, Calendar.SEPTEMBER, 2001), date(31, Calendar.OCTOBER, 2001));t10.setPercentComplete(0.2);s1.add(t10);final Task t12 = new Task("全部结束", date(28, Calendar.NOVEMBER, 2001), date(30, Calendar.NOVEMBER, 2001));t12.setPercentComplete(0.0);s1.add(t12);final TaskSeriesCollection collection = new TaskSeriesCollection();collection.add(s1);return collection;}}

转Base64图片字符串实现代码

想要转为base64图片字符串,就不能让JfreeChart生成图片,JfreeChart在底层生成图片的源代码中

我们可以发现,它是用BufferedImage转换输出的,所以我们重写这部分代码,修改工具类相关方法,比如多条折线图

           public static String testCreateManyLineChart(String[] lineTitle,List<String> xValue,String title,HashMap<String,Object> values,String xtitle,String ytitle){// 绘图数据集String re = null;try {DefaultCategoryDataset dataSet = new DefaultCategoryDataset();for (int i =0;i<lineTitle.length;i++) {for (int j=0;j<xValue.size();j++) {List<String> seriesList=(List)values.get("series"+Integer.valueOf(i+1));double d=Double.valueOf(seriesList.get(j).toString());dataSet.setValue(d,lineTitle[i],xValue.get(j));}}JFreeChart chart = createManyLineChart(dataSet, title, xtitle, ytitle);BufferedImage image = chart.createBufferedImage(1100, 600, 1, null);ByteArrayOutputStream stream = new ByteArrayOutputStream();ImageIO.write(image, "jpeg", stream);re ="data:image/jpeg;base64,"+ Base64.getEncoder().encodeToString(stream.toByteArray());re.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");} catch (IOException e) {e.printStackTrace();}return re;}

依赖

<!-- https://mvnrepository.com/artifact/jfree/jcommon --><dependency><groupId>jfree</groupId><artifactId>jcommon</artifactId><version>1.0.16</version></dependency><!-- https://mvnrepository.com/artifact/jfree/jfreechart --><dependency><groupId>jfree</groupId><artifactId>jfreechart</artifactId><version>1.0.13</version></dependency>

Java通过JfreeChart生成转Base64图片字符串(饼图、折线图、柱状图、折线图-多条、3D柱状图、气泡图、时序图、曲线图、区域图、分布图、联合分类图、双X轴图、K线图、柱状图-横向等图)相关推荐

  1. JAVA实现图片加水印及Base64图片字符串加水印

    JAVA实现图片加水印及Base64图片字符串加水印 可将根据不同需求选择场景一,场景二来实现家水印操作,个人感觉比我上一遍文章<base64字符串加水印 >实在 场景一: 涉及上送过来的 ...

  2. Java使用poi和jfreechart生成excel图表图片

    最近项目在频繁的操作excel,里边涉及到很多和图表有关的东西.有时候需要使用java操作excel自带的图标,比较复杂的我们都是使用excel模板的形式实现.  除此之外,也有一些功能只需要生成对应 ...

  3. HQChart实战教程23 - 点击K线显示历史分钟走势图

    HQChart实战教程23 - 点击K线显示历史分钟走势图 需求 步骤 1. 注册K线点击监听事件 2. 点击监听函数 使用网路回调函数请求历史分钟 交流QQ群:950092318 HQChart代码 ...

  4. Java | 将文字生成在空白图片居中位置(根据图片大小,自动调节文字大小)

    Java | 将文字生成在空白图片居中位置(根据图片大小,自动调节文字大小) 话不多说,直接上代码.(大家可以自己根据需要设置图片大小,不过图片过小时,字体会变模糊,尽量设置图片大一点,600~100 ...

  5. 小程序画布功能+JAVA用KUMO生成词云图片

    小程序画布功能+JAVA用KUMO生成词云图片 KUMO git地址:https://github.com/kennycason/kumo 原理:利用Kumo生成词云,并转换成64位传到小程序,小程序 ...

  6. 可视化篇(四)——— python绘制双y轴、箱线图、概率分布三种图形及案例

    可视化篇(四)--- python绘制双y轴.箱线图.概率分布三种图形及案例 摘要 绘制双y轴图形 绘制箱线图 绘制概率分布图 摘要 本文演示了如何通过python绘制双y轴.箱线图.概率分布三种图形 ...

  7. 通过http方式传递base64图片字符串无法还原成图片的问题

    在使用http协议传递base64图片字符串的过程中,一些特殊字符会在传输过程中发生改变或者被添加了换行. 所以需要转义这些特殊字符以便传值. String str = base64String.re ...

  8. python双坐标轴箱线图,python绘制双y轴、箱线图、概率分布三种图形及案例

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理. 本文演示了如何通过python绘制双y轴.箱线图.概率分布三种图形,并给出了具体案例源代码供 ...

  9. 实现ECharts双Y轴左右刻度线一致

    实现ECharts双Y轴左右刻度线一致 原文链接:https://blog.csdn.net/qq_40845885/article/details/82108525 博主亲测可用哦,先上图: 这是未 ...

最新文章

  1. Coursera Machine Learning 作业提交问题
  2. python模块调用的用法_如何使用Python语言中的random模块调用方法
  3. 基matlab的水果识别的应用,基于MATLAB的水果识别的数字图像处理
  4. ubuntu搭建tiny4412环境【学习笔记】
  5. mos管电路_【鼎阳硬件智库原创︱电源】 MOS管驱动电路的设计
  6. Migo估价记录不存在
  7. 远程开发 代码提示_VS Code 远程开发和代码评审实践
  8. C++中delete和delete[]的区别
  9. webflow如何使用_我如何使用Webflow构建辅助项目以帮助设计人员进行连接
  10. Javascript构造函数的继承
  11. Activity嵌套fragment大全,activity加载单个fragment,TabLayout+ViewPager实现多个fragment滑动效果
  12. VB.NET 中的 As New 以及型別指定
  13. 用渐变色画圆_详细步骤!用ps画个中秋圆月亮
  14. BI工具选型需考虑哪些问题
  15. 【转】字符串编辑距离
  16. Java:QQ登录页面的制作(实现成功登录的代码)——含源码
  17. 行业领先!5G投资1100亿! 20个中国移动5G成功案例分享( 业绩+案例 )
  18. mysql大于、小于符号的两种表示方法
  19. Cint() , int(),round() , fix() 的区别与联系
  20. 黑苹果10.15.7使用

热门文章

  1. python 输出三角形字符阵列 本题要求编写程序,输出n行由大写字母A开始构成的三角形字符阵列。
  2. SDNU1703字谜
  3. c语言程序能运行但屏幕不显示图片,c运行程序屏幕无显示!~~请高手指点!~~~...
  4. ①、HTML 简介实践学习
  5. iTOP-4412开发板10.1寸[金属框]屏幕硬件修改支持排线和HDMI
  6. Tabby-安装使用教程,可定制的跨平台终端神器,免费开源,ssh与sftp使用技巧,常用和高端功能介绍,多窗口显示
  7. java最基本的基础知识
  8. 虫师selenium3+python自动化测试电子版_Selenium3 Java自动化测试实战 第三版.pdf
  9. Axure 团队原型创建
  10. outlook 2016 邮件怎么显示图片