JFreeChart 生成图表,并为图表标注特殊点、添加文本标识框

news2025/2/5 8:09:23

一、项目场景:

Java使用JFreeChart库生成图片,主要场景为将具体的数据 可视化 生成曲线图等的图表。

本篇文章主要针对为数据集生成的图表添加特殊点及其标识框。具体包括两种场景:x轴为 时间戳 类型和普通 数值 类型。(y轴都为数值类型)

具体的效果图如下所示:

❀ x轴为 时间戳 形式
在这里插入图片描述

❀ x轴为 数值 形式
在这里插入图片描述


二、注意事项

前提介绍
这里 标注特殊点 以及 添加文本标识框 都不算是正规的方法,但是只要注意使 用,也是十分好用的。(正规的方法也能做,估计效果不一定ok)

实现方法: 利用JFreeChart一次可以将多个数据集渲染,也就是说可以一次画多条曲线(好像这种特性是普遍都有的QAQ),将所有的特殊点作为一个统一的数据集,放在整个(数据集)集合 的末尾。让集合的其它数据集正常渲染,然后取出最后一个特殊点数据集进行特殊样式化处理。比如:只显示点、点特殊显示、在点的附近添加文本注释框。这样做的好处就是:可以非常方便的添加多个特殊点。
(前提是特殊点一定是某个数据集的点位)

注意事项
🐟 多个数据集的命名不能重复,否则会出现某个数据集的数据不能正常显示;
在这里插入图片描述
在这里插入图片描述

🐟 如果添加的文本注释框需要换行功能,可惜JFreeChart中的XYTextAnnotation并不包括这个功能,即使在文本中手动添加 '\n' 也无法实现换行。这里采用添加多个注释框,再适当的调整位置,手动实现换行(也存在弊端,当图片缩放时,多行的文本注释框的内容可能会重叠或相隔太远的问题,笔者已经试着在解决这个问题了,但是效果仍未达到完美)

🐟 为特殊点添加文本注释框时,避免不了一个问题:当特殊点出现在图表边缘位置的时候,文本显示不完全。 这里呢,已经简单的根据x轴和y轴的数据范围进行了调整,也就是下面代码中annotationXPosFormatannotationYPosFormat 方法所完成的功能。
But,解决了但没完全解决!窗口的大小也与文本框的位置调整相关,这方面我还没完善,但是如果仅需要生成一张数据可视化图片(例如:报警图),意思是不涉及图片(窗口)大小的随意变化的画,下面的代码完全是够用的了。


三、代码记录

这里直接给出所有的代码:
依赖库

<!--        JFreeChart-->
<dependency>
   <groupId>org.jfree</groupId>
   <artifactId>jfreechart</artifactId>
   <version>1.5.3</version>
</dependency>

<!--        hutool-->
<dependency>
   <groupId>cn.hutool</groupId>
   <artifactId>hutool-all</artifactId>
   <version>5.8.16</version>
</dependency>

完整代码:

public class SpecialPointAnnotationFormat {
    public static void main(String[] args) {
        //创建主题样式 解决乱码(CN代表中文,这一步一定要添加)
        StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
        //设置标题字体
        standardChartTheme.setExtraLargeFont(new Font("宋体", Font.BOLD, 15));
        //设置图例的字体
        standardChartTheme.setRegularFont(new Font("宋体", Font.PLAIN, 12));
        //设置轴向的字体
        standardChartTheme.setLargeFont(new Font("宋体", Font.BOLD, 12));
        //设置主题样式
        ChartFactory.setChartTheme(standardChartTheme);

        // 展示x轴为时间戳的图表
//        showXTimeSeriesChart(1600,1000);
//        showXTimeSeriesChart(1200,750);
//        showXTimeSeriesChart(800,500);
//        showXTimeSeriesChart(400,250);
        // 建议的图片大小
        showXTimeSeriesChart(1000,800);

        // 展示x轴为普通数值的图表
//        showXNumberSeriesChart(1000,800);
    }

    // 展示x轴为普通数值的图表
    private static void showXNumberSeriesChart(int width,int height){
        // 准备数据
        XYSeries xySeries = new XYSeries("Data");
        // 报警点
        double xValue = 52.15d;
        double yValue = 22.15d;

		// 手动初始化数据集
        int dataSize = 200;
        xySeries.add(0.5,-0.05);
        for(int i=1;i<dataSize;i++){
//        for(int i=0;i<dataSize;i++){
            if(i == 100){
                xySeries.add(xValue,yValue);
                continue;
            }
            xySeries.add(getRandomDouble(dataSize),getRandomDouble(dataSize));
        }

		// 整个数据集的集合seriesCollection 
        XYSeriesCollection seriesCollection = new XYSeriesCollection();
        seriesCollection.addSeries(xySeries);

        // 创建示例数据集
        XYDataset dataset = seriesCollection;

        // 创建图表
        JFreeChart chart = ChartFactory.createXYLineChart(
                "XYTextAnnotation Example",
                "X",
                "Y",
                dataset
        );

        // 获取图表的绘图区域
        XYPlot plot = chart.getXYPlot();

        // 设置曲线颜色
        plot.getRenderer().setSeriesPaint(0, Color.decode("#2586CC"));
        // 设置图表背景颜色
        plot.setBackgroundPaint(Color.WHITE);
        plot.setDomainGridlinePaint(Color.WHITE);
        plot.setRangeGridlinePaint(Color.WHITE);
        plot.setAxisOffset(new RectangleInsets(15.0, 5.0, 5.0, 5.0));
        plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

        // 找到报警点对应的值
        Optional alarmOption = xySeries.getItems().stream().filter(obj -> {
            XYDataItem dataItem = (XYDataItem) obj;
            return NumberUtil.equals(dataItem.getXValue(), xValue) && NumberUtil.equals(dataItem.getYValue(), yValue);
        }).findFirst();
        if(alarmOption.isPresent()){
            XYDataItem alarmItem = (XYDataItem) alarmOption.get();
            addNumberSpecialPoint(plot,xySeries,alarmItem,"报警点","now","value");
        }else {
            System.out.println("未在数据集中找到报警点....");
        }

        // 找到值最大的点
        Optional<XYDataItem> maxOption = xySeries.getItems().stream().max(Comparator.comparingDouble(XYDataItem::getYValue));
        if (maxOption.isPresent()) {
            XYDataItem maxDataItem = maxOption.get();
            addNumberSpecialPoint(plot,xySeries,maxDataItem,"报警点","报警点","报警值");
        }
        // 找到值最小的点
        Optional<XYDataItem> minOption = xySeries.getItems().stream().min(Comparator.comparingDouble(XYDataItem::getYValue));
        if (minOption.isPresent()) {
            XYDataItem minDataItem = minOption.get();
            addNumberSpecialPoint(plot,xySeries,minDataItem,"报警点","报警点","报警值");
        }

        // 创建图表窗口并显示图表
        ChartFrame frame = new ChartFrame("x轴为数值类型的曲线图", chart);
        frame.setPreferredSize(new Dimension(width, height));
        frame.pack();
        frame.setVisible(true);
    }

    // 展示x轴为时间戳的图表
    private static void showXTimeSeriesChart(int width,int height){
        LocalDateTime alarmTime = LocalDateTime.now();

        LocalDateTime dateTime = alarmTime.minusMinutes(5l).minusSeconds(30l);

        TimeSeries series = new TimeSeries("Data");

		// 手动初始化数据集
        int num = 200;
        series.add(new Millisecond(Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant())),-12.5d);
//        for(int i=1;i<num;i++){
//        for(int i=0;i<num;i++){
        for(int i=1;i<num-1;i++){
            series.add(new Millisecond(Date.from(dateTime.plusSeconds((long)3*i).atZone(ZoneId.systemDefault()).toInstant())),getRandomDouble(num));
        }
        series.add(new Millisecond(Date.from(dateTime.plusSeconds((long)3*(num-1)).atZone(ZoneId.systemDefault()).toInstant())),num + 21.5);

		// 整个数据集的集合seriesCollection 
        TimeSeriesCollection seriesCollection = new TimeSeriesCollection();
        seriesCollection.addSeries(series);

        // 创建示例数据集
        XYDataset dataset = seriesCollection;

        // 创建曲线图
        JFreeChart chart = ChartFactory.createTimeSeriesChart(
                "", // 图表标题
                "", // X轴标签
                "", // Y轴标签
                dataset // 数据集
        );

        // 获取图表的绘图区域
        XYPlot plot = chart.getXYPlot();

        // 设置曲线颜色
        plot.getRenderer().setSeriesPaint(0, Color.decode("#2586CC"));
        // 设置图表背景颜色
        plot.setBackgroundPaint(Color.WHITE);
        plot.setDomainGridlinePaint(Color.WHITE);
        plot.setRangeGridlinePaint(Color.WHITE);
        plot.setAxisOffset(new RectangleInsets(15.0, 5.0, 5.0, 5.0));
        plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

        // 找到报警点对应的值
        // 将报警时间转换为毫秒表示
        long alarmTimeMillis = alarmTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        Optional alarmOptional = series.getItems().stream().filter(obj -> {
            long firstMillisecond = ((TimeSeriesDataItem) obj).getPeriod().getFirstMillisecond();
            return firstMillisecond == alarmTimeMillis;
        }).findFirst();
        if(alarmOptional.isPresent()){
            TimeSeriesDataItem alarmItem = (TimeSeriesDataItem) alarmOptional.get();
            addTimeSpecialPoint(plot,series,alarmItem,"报警点", "now","value");
        }else {
            System.out.println("未在数据集中找到报警点....");
        }

        // 找到值最大的点(一般值最大的点为报警点)
        Optional<TimeSeriesDataItem> maxOption = series.getItems().stream().max(Comparator.comparingDouble(item -> ((TimeSeriesDataItem) item).getValue().doubleValue()));
        if (maxOption.isPresent()) {
            TimeSeriesDataItem maxDataItem = maxOption.get();
            addTimeSpecialPoint(plot,series,maxDataItem,"报警点","报警时间","报警点");
        }
        // 找到值最小的点(一般值最大的点为报警点)
        Optional<TimeSeriesDataItem> minOption = series.getItems().stream().min(Comparator.comparingDouble(item -> ((TimeSeriesDataItem) item).getValue().doubleValue()));
        if (minOption.isPresent()) {
            TimeSeriesDataItem minDataItem = minOption.get();
            addTimeSpecialPoint(plot,series,minDataItem,"报警点","报警时间","报警点");
        }

        double xRange = plot.getDomainAxis().getRange().getLength();
        double yRange = plot.getRangeAxis().getRange().getLength();

        // 创建图表窗口并显示图表
        ChartFrame frame = new ChartFrame("x轴为时间戳类型的曲线图", chart);
        frame.setPreferredSize(new Dimension(width,height));
        frame.pack();// pack会默认渲染为frame的最佳尺寸
        frame.setVisible(true);

		// 这里也可以直接生成一张图片存放到指定位置(path)
        // 生成一张图片
//        try {
//            ByteArrayOutputStream out = new ByteArrayOutputStream();
//            ChartUtils.writeChartAsJPEG(out, chart, 1000, 800);
//            String path = System.getProperty("user.dir") + "\\images\\image.jpg";
//
//            downloadByteArrayOutputStream(out.toByteArray(), path);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
    }

    public static void downloadByteArrayOutputStream(byte[] data, String outputPath) {
        try {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
            FileOutputStream outputStream = new FileOutputStream(outputPath);

            // 将字节数组写入到文件
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流
            inputStream.close();
            outputStream.close();

            System.out.println("文件下载完成:" + outputPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 图表添加特殊点(x轴为数值类型:double)
     * @param plot 图层
     * @param xySeries 一个chart可以有多个数据集(多条折线),需要标识为哪个数据集添加特殊点
     * @param dataItem 需要标识的点
     * @param specialTextTitle 特殊点集合名称标识(可置为“”,注意不同数据集的名称不可重复)
     * @param xSpecialText 特殊点对应的x轴的提示内容
     * @param ySpecialText 特殊点对应的y轴的提示内容
     */
    private static void addNumberSpecialPoint(XYPlot plot,
                                              XYSeries xySeries ,
                                              XYDataItem dataItem,
                                              String specialTextTitle,
                                              String xSpecialText,
                                              String ySpecialText){
        XYSeriesCollection seriesCollection = (XYSeriesCollection) plot.getDataset();

        XYItemRenderer r = plot.getRenderer();
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;

        double xValue = dataItem.getXValue();
        double yValue = dataItem.getYValue();

        // 设置特殊点的集合
        // 判断特殊点集合之前是否已创建
        XYSeries specialSeries = null;
        int seriesSize = seriesCollection.getSeries().size();
        if(seriesSize > 1){
            specialSeries = (XYSeries)seriesCollection.getSeries().get(seriesSize-1);
            // 再判断特殊点是否已添加
            Optional optional = specialSeries.getItems().stream().filter(item -> {
                XYDataItem xyDataItem = (XYDataItem) item;
                return NumberUtil.equals(xValue, xyDataItem.getXValue()) && NumberUtil.equals(yValue, xyDataItem.getYValue());
            }).findFirst();
            if(optional.isPresent()){
                // 特殊点已经添加
                return;
            }
        }else {
            specialSeries = new XYSeries(specialTextTitle);
            seriesCollection.addSeries(specialSeries);
        }

        // 添加特殊值
        specialSeries.add(xValue,yValue);

        // 格式
        // 设置文本颜色和透明度
        Color textColor = new Color(255, 0, 0, 128); // 设置为半透明的红色(透明度为 128)
        Font font = new Font("SansSerif", Font.BOLD, 12);

        // 创建一个带文字的注释框
        String alarmText1 = xSpecialText + ":" + xValue;
        XYTextAnnotation line1 = new XYTextAnnotation(alarmText1,xValue,yValue);
        line1.setFont(font);
        line1.setPaint(textColor);
        line1.setX((double) annotationXPosFormat(plot,xySeries,xValue, TextAnnotationTypeEnum.DOUBLE.getType()));
        line1.setY(annotationYPosFormat(plot,xySeries,yValue,TextAnnotationTypeEnum.DOUBLE.getType()));
        plot.addAnnotation(line1);

        double lineSpace = 3.0; // 3
        Optional<XYDataItem> maxOption = xySeries.getItems().stream().max(Comparator.comparingDouble(XYDataItem::getYValue));
        Optional<XYDataItem> minOption = xySeries.getItems().stream().min(Comparator.comparingDouble(XYDataItem::getYValue));
        if(maxOption.isPresent() && minOption.isPresent()) {
            double sub = maxOption.get().getYValue() - minOption.get().getYValue();
            lineSpace = sub/50;
        }
        String alarmText2 = ySpecialText + ":" + yValue;
        XYTextAnnotation line2 = new XYTextAnnotation(alarmText2,xValue,yValue);
        line2.setFont(font);
        line2.setPaint(textColor);
        line2.setX((double)annotationXPosFormat(plot,xySeries,xValue,TextAnnotationTypeEnum.DOUBLE.getType()));
        line2.setY(annotationYPosFormat(plot,xySeries,yValue,TextAnnotationTypeEnum.DOUBLE.getType())-lineSpace);
        plot.addAnnotation(line2);

        int pointSize = 3;
        Shape specifiedShape = new Ellipse2D.Double(-(pointSize*2), -(pointSize*2), pointSize*2, pointSize*2); // 指定点显示的形状
        Paint specifiedPaint = Color.RED; // 指定点显示的颜色

        // 对某个指定序列集合的点进行操作
        renderer.setSeriesShapesVisible(seriesCollection.getSeriesCount() - 1, true); // 显示指定点的形状
        renderer.setSeriesShape(seriesCollection.getSeriesCount() - 1, specifiedShape); // 设置指定点的形状
        renderer.setSeriesPaint(seriesCollection.getSeriesCount() - 1, specifiedPaint); // 设置指定点的颜色
        // 特殊点只显示点,而不显示曲线
        renderer.setSeriesLinesVisible(seriesCollection.getSeriesCount() - 1, false); // 不显示曲线
        renderer.setSeriesShapesVisible(seriesCollection.getSeriesCount() - 1, true); // 显示点
    }

    /**
     * 图表添加特殊点(x轴为时间戳类型)
     * @param plot 图层
     * @param timeSeries 一个chart可以有多个数据集(多条折线),需要标识为哪个数据集添加特殊点
     * @param dataItem 需要标识的点
     * @param specialTextTitle 特殊点集合名称标识(可置为“”,注意不同数据集的名称不可重复)
     * @param xSpecialText 特殊点对应的x轴的提示内容
     * @param ySpecialText 特殊点对应的y轴的提示内容
     */
    private static void addTimeSpecialPoint(XYPlot plot,
                                            TimeSeries timeSeries ,
                                            TimeSeriesDataItem dataItem,
                                            String specialTextTitle,
                                            String xSpecialText,
                                            String ySpecialText){
        TimeSeriesCollection seriesCollection = (TimeSeriesCollection) plot.getDataset();

        XYItemRenderer r = plot.getRenderer();
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;

        long xValue = dataItem.getPeriod().getFirstMillisecond();
        double yValue = dataItem.getValue().doubleValue();

        // 设置特殊点的集合
        // 判断特殊点集合之前是否已创建
        TimeSeries specialSeries = null;
        int seriesSize = seriesCollection.getSeries().size();
        if(seriesSize > 1){
            specialSeries = (TimeSeries)seriesCollection.getSeries().get(seriesSize-1);
            // 再判断特殊点是否已添加
            Optional optional = specialSeries.getItems().stream().filter(item -> {
                TimeSeriesDataItem timeDataItem = (TimeSeriesDataItem) item;
                return NumberUtil.equals(xValue, timeDataItem.getPeriod().getFirstMillisecond()) && NumberUtil.equals(yValue, timeDataItem.getValue().doubleValue());
            }).findFirst();
            if(optional.isPresent()){
                // 特殊点已经添加
                return;
            }
        }else {
            specialSeries = new TimeSeries(specialTextTitle);
            seriesCollection.addSeries(specialSeries);
        }

        // 添加特殊值
        specialSeries.add(dataItem.getPeriod(),dataItem.getValue().doubleValue());

        // 格式
        // 设置文本颜色和透明度
        Color textColor = new Color(255, 0, 0, 128); // 设置为半透明的红色(透明度为 128)
        Font font = new Font("SansSerif", Font.BOLD, 12);

        // 创建一个带文字的注释框
        String alarmText1 = ySpecialText + ":" + yValue;
        XYTextAnnotation line1 = new XYTextAnnotation(alarmText1,xValue,yValue);
        line1.setFont(font);
        line1.setPaint(textColor);
        line1.setX((long)annotationXPosFormat(plot,timeSeries,xValue, TextAnnotationTypeEnum.TIME.getType()));
        line1.setY(annotationYPosFormat(plot,timeSeries,yValue,TextAnnotationTypeEnum.TIME.getType()));
        plot.addAnnotation(line1);

        /**
         * 通过获取font获取一行字的行高
         */
//        // 设置XYTextAnnotation之间的行间距
//        // 获取font的行高
//        FontMetrics fontMetrics = Toolkit.getDefaultToolkit().getFontMetrics(font);
//        int lineHeight = fontMetrics.getHeight();
//        // 250->1.2 | 500->0.6 | 750->0.3 | 1000->0.2
//        double lineSpace = lineHeight + xx;
//        System.out.println("lineSpace=" + lineSpace);
//        System.out.println("xx=" + xx);

        // 设置换行的间隔
        double lineSpace = 3.0; // 3
        Optional<TimeSeriesDataItem> maxOption = timeSeries.getItems().stream().max(Comparator.comparingDouble(item -> ((TimeSeriesDataItem) item).getValue().doubleValue()));
        Optional<TimeSeriesDataItem> minOption = timeSeries.getItems().stream().min(Comparator.comparingDouble(item -> ((TimeSeriesDataItem) item).getValue().doubleValue()));
        if(maxOption.isPresent() && minOption.isPresent()) {
            double sub = maxOption.get().getValue().doubleValue() - minOption.get().getValue().doubleValue();
            lineSpace = sub/50;
        }

        String alarmText2 = xSpecialText + ":" + LocalDateTime.ofInstant(Instant.ofEpochMilli(xValue), ZoneId.systemDefault()).format(DatePattern.NORM_TIME_FORMATTER);
        XYTextAnnotation line2 = new XYTextAnnotation(alarmText2,xValue,yValue);
        line2.setFont(font);
        line2.setPaint(textColor);
        line2.setX((long)annotationXPosFormat(plot,timeSeries,xValue,TextAnnotationTypeEnum.TIME.getType()));
        line2.setY(annotationYPosFormat(plot,timeSeries,yValue,TextAnnotationTypeEnum.TIME.getType())-lineSpace);
        plot.addAnnotation(line2);

        int dotSize = 3;
        Shape specifiedShape = new Ellipse2D.Double(-(dotSize*2), -(dotSize*2), dotSize*2, dotSize*2); // 指定点显示的形状
        Paint specifiedPaint = Color.RED; // 指定点显示的颜色

        // 对特殊点集合的点进行操作()
        renderer.setSeriesShapesVisible(seriesCollection.getSeriesCount() - 1, true); // 显示指定点的形状
        renderer.setSeriesShape(seriesCollection.getSeriesCount() - 1, specifiedShape); // 设置指定点的形状
        renderer.setSeriesPaint(seriesCollection.getSeriesCount() - 1, specifiedPaint); // 设置指定点的颜色
        // 特殊点只显示点,而不显示曲线
        renderer.setSeriesLinesVisible(seriesCollection.getSeriesCount() - 1, false); // 不显示曲线
        renderer.setSeriesShapesVisible(seriesCollection.getSeriesCount() - 1, true); // 显示点
    }

    /**
     * XYTextAnnotation 文本框位置(x)调整(防止文本框处于边缘位置导致的文本显示不全)
     * @param series 数据集合
     * @param value x轴的值
     * @param type x轴值的类型(有时间戳类型[long]和数值类型[double])
     * @return 返回值与type的入参类型相同(方法调用处需要类型转换)
     */
    private static Object annotationXPosFormat(XYPlot plot,Series series, Object value, String type){
        // x轴的范围
        double xRange = plot.getDomainAxis().getRange().getLength();
        double offset = xRange * 0.05;

        if(TextAnnotationTypeEnum.TIME.getType().equals(type)){
            // x轴为时间戳形式
            long xValue = (long) value;
            TimeSeries timeSeries = (TimeSeries) series;
            int size = timeSeries.getItems().size();

            long maxValue = timeSeries.getDataItem(size - 1).getPeriod().getFirstMillisecond();
            long minValue = timeSeries.getDataItem(0).getPeriod().getFirstMillisecond();
            if(xValue - minValue <= offset){
                return xValue + (long)offset;
            }
            if(maxValue - xValue <= offset){
                return xValue - (long)offset;
            }
            return xValue;
        }
        else if(TextAnnotationTypeEnum.DOUBLE.getType().equals(type)){
            // x轴为double形式
            double xValue = (double) value;
            XYSeries xySeries = (XYSeries) series;

            Optional<XYDataItem> maxOption = xySeries.getItems().stream().max(Comparator.comparingDouble(XYDataItem::getXValue));
            Optional<XYDataItem> minOption = xySeries.getItems().stream().min(Comparator.comparingDouble(XYDataItem::getXValue));
            if(minOption.isPresent() && xValue - minOption.get().getXValue() <= offset){
                return xValue + offset;
            }
            if(maxOption.isPresent() && maxOption.get().getXValue() - xValue <= offset){
                return xValue - offset;
            }
            return xValue;
        }
        else {
            return value;
        }
    }

    /**
     *  XYTextAnnotation 文本框位置(y)调整(防止文本框处于边缘位置导致的文本显示不全)
     * @param series 数据集合
     * @param yValue y轴的值
     * @param type x轴值的类型(有时间戳类型[long]和数值类型[double])
     * @return 统一为double
     */
    private static double annotationYPosFormat(XYPlot plot ,Series series,double yValue,String type){
        // y轴值的范围
        double yRange = plot.getRangeAxis().getRange().getLength();
        double offset = yRange * 0.05;

        // y轴一般都为double类型
        if(TextAnnotationTypeEnum.TIME.getType().equals(type)){
            TimeSeries timeSeries = (TimeSeries) series;

            Optional<TimeSeriesDataItem> maxOption = timeSeries.getItems().stream().max(Comparator.comparingDouble(item -> ((TimeSeriesDataItem) item).getValue().doubleValue()));
            Optional<TimeSeriesDataItem> minOption = timeSeries.getItems().stream().min(Comparator.comparingDouble(item -> ((TimeSeriesDataItem) item).getValue().doubleValue()));
            if(maxOption.isPresent() && minOption.isPresent()){
                double minValue = minOption.get().getValue().doubleValue();
                double maxValue = maxOption.get().getValue().doubleValue();
                if(minOption.isPresent() && yValue - minValue <= offset){
                    return yValue + offset;
                }
                if(maxOption.isPresent() && maxValue - yValue <= offset){
                    return yValue - offset/3;
                }
                return yValue - offset/3;
            }
            return yValue;
        }
        else if(TextAnnotationTypeEnum.DOUBLE.getType().equals(type)){
            XYSeries xySeries = (XYSeries) series;

            Optional<XYDataItem> maxOption = xySeries.getItems().stream().max(Comparator.comparingDouble(XYDataItem::getYValue));
            Optional<XYDataItem> minOption = xySeries.getItems().stream().min(Comparator.comparingDouble(XYDataItem::getYValue));
            if(maxOption.isPresent() && minOption.isPresent()){
                if(minOption.isPresent() && yValue - minOption.get().getYValue() <= offset){
                    return yValue + offset;
                }
                if(maxOption.isPresent() && maxOption.get().getYValue() - yValue <= offset){
                    return yValue - offset/3;
                }
                return yValue - offset/3;
            }
            return yValue;
        }
        else {
            return yValue;
        }
    }

    /**
     * 获取指定范围的double类型的随机数
     * @param scale 范围
     */
    private static Double getRandomDouble(Integer scale){
        Random random = new Random();
        double randomNumber = random.nextDouble() * scale; // 生成0到100之间的随机小数

        BigDecimal bigDecimal = BigDecimal.valueOf(randomNumber).setScale(2, RoundingMode.HALF_DOWN);

        return bigDecimal.doubleValue();
    }
}



🐟
bye!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1328256.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringMVC:执行原理详解、配置文件和注解开发实现 SpringMVC

文章目录 SpringMVC - 01一、概述二、SpringMVC 执行原理三、使用配置文件实现 SpringMVC四、使用注解开发实现 SpringMVC1. 步骤2. 实现 五、总结注意&#xff1a; SpringMVC - 01 一、概述 SpringMVC 官方文档&#xff1a;点此进入 有关 MVC 架构模式的内容见之前的笔记&a…

VM——计算流程执行耗时

1、计算同一个流程内的耗时&#xff0c;可以直接用“耗时统计”模块&#xff1b; 2、计算多个流程的运行耗时&#xff0c;需要使用“脚本”&#xff0c;利用C#函数计算耗时 首先&#xff0c;记录起始时间&#xff0c;保存到string类型的全局变量中&#xff0c; curTmStr Dat…

c#委托学习笔记1

委托三步骤 第一步&#xff1a;定义委托 //第一步&#xff1a;1 声明委托(定义委托) //对于声明委托的解释如下&#xff1a; //解释a&#xff1a;函数指针 //解释b&#xff1a;委托就是定义函数的形状&#xff08;形态&#xff09; // 即&#xff1a;返回值类型&#x…

php学习01-Hello World

开发环境搭建 参考 如果没有搭建的请参考上面的文章进行搭建 新建index.php <?php echo Hello World; ?>访问 修改index.php代码 <?php phpinfo() //主要是用来打印php的一些配置信息方便后期排查配置是否正确以及插件是否开启 ?>

conda环境下执行conda命令提示无法识别解决方案

1 问题描述 win10环境命令行执行conda命令&#xff0c;报命令无法识别&#xff0c;错误信息如下&#xff1a; PS D:\code\cv> conda activate pt conda : 无法将“conda”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写&#xff0c;如果包括路径&a…

3分钟看懂如何给开源项目发起提案

背景 前段时间在使用 Pulsar 的 admin API 时&#xff0c;发现其中的一个接口响应非常慢&#xff1a; admin.topics().getPartitionedStats(topic); 使用 curl 拿到的响应结果非常大&#xff0c;同时也非常耗时&#xff1a; 具体的 issue 在这里&#xff1a;https://github.…

idea 远程调试linux上的代码

背景介绍 开发过程中&#xff0c;我们经常会遇到部署的代码运行出问题、看日志由不是很直观、我们希望可以像调试本地代码一样去调试远程代码; IDEA提供了Remote工具,基于JVM的跨平台能力&#xff0c;我们可以远程调试部署的代码。 前提 保证远程和本地跑的代码是一致的 操…

陶建辉在 CIAS 2023 谈“新能源汽车的数字化”

近年&#xff0c;中国的新能源汽车发展迅猛&#xff0c;在全球竞争中表现出色&#xff0c;已经连续 8 年保持全球销量第一。在新兴技术的推动下&#xff0c;新能源汽车的数字化转型也正在加速进行&#xff0c;从汽车制造到能源利用、人机交互&#xff0c;各个环节都在进行数字化…

Pooling方法总结(语音识别)

Pooling layer将变长的frame-level features转换为一个定长的向量。 1. Statistics Pooling 链接&#xff1a;http://danielpovey.com/files/2017_interspeech_embeddings.pdf The default pooling method for x-vector is statistics pooling. The statistics pooling laye…

2024海外社媒营销新趋势,品牌出海如何做?

社交媒体在网上的影响力是毋庸置疑的。投资社交媒体平台并建立公司形象&#xff0c;提高产品运营收入&#xff0c;提升品牌知名度&#xff0c;对于吸引对您所提供的产品感兴趣的人至关重要。 然而&#xff0c;社交媒体格局总是在变化&#xff0c;这意味着您需要掌握新的社交媒…

LeetCode Hot100 295.数据流的中位数

题目&#xff1a; 中位数是有序整数列表中的中间值。如果列表的大小是偶数&#xff0c;则没有中间值&#xff0c;中位数是两个中间值的平均值。 例如 arr [2,3,4] 的中位数是 3 。例如 arr [2,3] 的中位数是 (2 3) / 2 2.5 。 实现 MedianFinder 类: MedianFinder() 初始…

Java:获取线程组的最大优先级

java.lang.ThreadGroup的getMaxPriority()函数返回该线程组的最大优先级。这个最大优先级就等于该线程组中新创建线程的最大优先级。 代码示例&#xff1a; package com.thb;public class Test5 {public static void main(String[] args) {ThreadGroup threadGroup Thread.c…

转义字符使用详解【C语言】

目录 转义字符的概念 转义字符表 转义字符详解 和 实际使用示例 一、\a 二、\b 三、\f 四、\n 五、\r 六、\t 七、\v 八、\\ 九、\ 十、\" 十一、\? 十二、\0 十三、\ddd 十四、\xhh 总结—— 转义字符的概念 所有的 ASCII码都可以用“\加数字” 来表示…

【C语言刷题每日一题#牛客网BC69】——空心正方形图案

目录 问题描述 思路分析 代码实现 结果测试 问题描述 思路分析 首先根据输入的描述&#xff0c;多组输入需要将scanf放在循环中来实现分析输出的规律&#xff1a;当输入为4时&#xff0c;分别在第0行和第3行&#xff08;4-1行&#xff09;&#xff0c;第0列和第3列&#xf…

Sentinel 流量治理组件教程

前言 官网首页&#xff1a;home | Sentinel (sentinelguard.io) 随着微服务的流行&#xff0c;服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式、多语言异构化服务架构的流量治理组件&#xff0c;主要以流量为切入点&#xff0c;从流量路由、流量控制、流量整形…

PHP开发日志——循环和条件语句嵌套不同,效率不同(循环内加入条件语句,条件语句判断后加入循环,array_map函数中加入条件语句)

十多年前开发框架时&#xff0c;为了效率不断试过各种代码写法&#xff0c;今天又遇到了&#xff0c;想想php8时代会不会有所变化&#xff0c;结果其实也还是和当年一样&#xff0c;但当年没写博客&#xff0c;但现在可以把数据记录下来了。 PHP_loop_ireflies_dark_forest 项目…

【SpringBoot】之Security集成使用(入门级)

&#x1f389;&#x1f389;欢迎来到我的CSDN主页&#xff01;&#x1f389;&#x1f389; &#x1f3c5;我是君易--鑨&#xff0c;一个在CSDN分享笔记的博主。&#x1f4da;&#x1f4da; &#x1f31f;推荐给大家我的博客专栏《SpringBoot开发之Security系列》。&#x1f3af…

数据恢复工具推荐!这3款堪称删除文件恢复大师!

“快看看我&#xff01;经常都会莫名奇妙丢失各种电脑文件&#xff0c;但是又无法通过简单的方法找回重要的数据&#xff0c;有没有什么简单的操作可以帮助我快速恢复数据的呀&#xff1f;非常感谢&#xff01;” 在我们的日常生活中&#xff0c;无论是工作还是学习&#xff0c…

软考中级应该选哪个?

选择软考中级科目&#xff0c;应该怎么做&#xff1f; 1.1 软考中级科目有哪些可供选择&#xff1f; 1.2 如何选择适合自己的软考中级科目&#xff1f; 系统集成项目管理工程师真的容易吗&#xff1f; 如何在软考中级阶段选择科目&#xff1f;软考中级共有15个科目。软考共…

鸿蒙开发基本概念

1、开发准备 1.1、UI框架 HarmonyOS提供了一套UI开发框架&#xff0c;即方舟开发框架&#xff08;ArkUI框架&#xff09;。方舟开发框架可为开发者提供应用UI开发所必需的能力&#xff0c;比如多种组件、布局计算、动画能力、UI交互、绘制等。 方舟开发框架针对不同目的和技术…