Example usage for org.jfree.chart.renderer.xy XYItemRenderer setSeriesStroke

List of usage examples for org.jfree.chart.renderer.xy XYItemRenderer setSeriesStroke

Introduction

In this page you can find the example usage for org.jfree.chart.renderer.xy XYItemRenderer setSeriesStroke.

Prototype

public void setSeriesStroke(int series, Stroke stroke);

Source Link

Document

Sets the stroke used for a series and sends a RendererChangeEvent to all registered listeners.

Usage

From source file:org.gumtree.vis.awt.time.TimePlotPanel.java

protected void selectSeries(IDataset dataset, int seriesIndex) {
    if (dataset != null && seriesIndex >= 0) {
        //         if (selectedDataset != null && selectedSeriesIndex >= 0 && 
        //               (selectedDataset != dataset || selectedSeriesIndex != seriesIndex)) {
        //            XYItemRenderer renderer = getChart().getXYPlot().getRendererForDataset(
        //                  selectedDataset);
        //            if (renderer instanceof XYLineAndShapeRenderer) {
        //               renderer.setSeriesStroke(selectedSeriesIndex, DEFAULT_STROCK);
        //            }
        //         }

        boolean isSelected = false;
        if (selectedDataset != dataset || selectedSeriesIndex != seriesIndex) {
            XYItemRenderer renderer = getChart().getXYPlot().getRendererForDataset(dataset);
            if (renderer instanceof XYLineAndShapeRenderer) {
                renderer.setSeriesStroke(seriesIndex, BOLD_STROCK);
                isSelected = true;//  w  w  w .  j ava2  s .c  om
            }
            ValueAxis axis = getXYPlot().getRangeAxisForDataset(getXYPlot().indexOf(dataset));
            //            Font titleFont = axis.getLabelFont();
            //            axis.setLabelFont(titleFont.deriveFont(Font.BOLD));
            axis.setLabelPaint(AXIS_FOCUS_COLOR);
            //            Font tickFont = axis.getTickLabelFont();
            //            axis.setTickLabelFont(tickFont.deriveFont(Font.BOLD));
            axis.setTickLabelPaint(AXIS_FOCUS_COLOR);
            //            axis.setVisible(true);
        }
        Stroke strokeToSet = isSelected ? SHALLOW_STROCK : DEFAULT_STROCK;
        for (int i = 0; i < getXYPlot().getDatasetCount(); i++) {
            IDataset xyDataset = (IDataset) getXYPlot().getDataset(i);
            if (xyDataset == null) {
                continue;
            }
            XYItemRenderer renderer = getXYPlot().getRendererForDataset(xyDataset);
            if (renderer != null && renderer instanceof XYLineAndShapeRenderer) {
                for (int j = 0; j < xyDataset.getSeriesCount(); j++) {
                    if (dataset != xyDataset || seriesIndex != j) {
                        renderer.setSeriesStroke(j, strokeToSet);
                    }
                }
            }
            if (dataset != xyDataset) {
                ValueAxis axis = getXYPlot().getRangeAxisForDataset(i);
                //               Font titleFont = axis.getLabelFont();
                //               axis.setLabelFont(titleFont.deriveFont(Font.PLAIN));
                axis.setLabelPaint(AXIS_SHALLOW_COLOR);
                //               Font tickFont = axis.getTickLabelFont();
                //               axis.setTickLabelFont(tickFont.deriveFont(Font.PLAIN));
                axis.setTickLabelPaint(AXIS_SHALLOW_COLOR);
                //               axis.setVisible(false);
            }
        }
    } else if (selectedDataset != null && selectedSeriesIndex >= 0) {
        //         XYItemRenderer renderer = getChart().getXYPlot().getRendererForDataset(
        //               selectedDataset);
        //         if (renderer instanceof XYLineAndShapeRenderer) {
        //            renderer.setSeriesStroke(selectedSeriesIndex, DEFAULT_STROCK);
        //         }
        for (int i = 0; i < getXYPlot().getDatasetCount(); i++) {
            IDataset xyDataset = (IDataset) getXYPlot().getDataset(i);
            if (xyDataset == null) {
                continue;
            }
            XYItemRenderer renderer = getXYPlot().getRendererForDataset(xyDataset);
            if (renderer != null && renderer instanceof XYLineAndShapeRenderer) {
                for (int j = 0; j < xyDataset.getSeriesCount(); j++) {
                    renderer.setSeriesStroke(j, DEFAULT_STROCK);
                }
            }
            ValueAxis axis = getXYPlot().getRangeAxisForDataset(i);
            //            Font titleFont = axis.getLabelFont();
            //            axis.setLabelFont(titleFont.deriveFont(Font.PLAIN));
            //            Font tickFont = axis.getTickLabelFont();
            //            axis.setTickLabelFont(tickFont.deriveFont(Font.PLAIN));
            axis.setLabelPaint(AXIS_FOCUS_COLOR);
            axis.setTickLabelPaint(AXIS_FOCUS_COLOR);
            //            axis.setVisible(true);
        }
    }
    selectedSeriesIndex = seriesIndex;
    selectedDataset = dataset;
    updatePlot();
}

From source file:org.codehaus.mojo.dashboard.report.plugin.chart.time.TimeChartRenderer.java

public void createChart() {
    XYDataset dataset = (XYDataset) this.datasetStrategy.getDataset();
    report = ChartFactory.createTimeSeriesChart(this.datasetStrategy.getTitle(), // title
            this.datasetStrategy.getXAxisLabel(), // x-axis label
            this.datasetStrategy.getYAxisLabel(), // y-axis label
            dataset, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );/*from ww  w .jav a2  s. co m*/

    // report.setBackgroundPaint( Color.lightGray );
    XYPlot plot = report.getXYPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
    XYItemRenderer xyitemrenderer = plot.getRenderer();
    if (xyitemrenderer instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyitemrenderer;
        renderer.setBaseShapesVisible(true);
        renderer.setBaseShapesFilled(true);

        renderer.setBaseShapesVisible(true);
        renderer.setDrawOutlines(true);
        renderer.setBaseItemLabelGenerator(
                ((AbstractTimeChartStrategy) this.datasetStrategy).getLabelGenerator());
        renderer.setBaseItemLabelFont(new Font("SansSerif", Font.BOLD, 10));
        renderer.setBaseItemLabelsVisible(true);
        renderer.setBasePositiveItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE10, TextAnchor.BASELINE_RIGHT));
    }

    Paint[] paints = this.datasetStrategy.getPaintColor();
    for (int i = 0; i < dataset.getSeriesCount() && i < paints.length; i++) {
        xyitemrenderer.setSeriesPaint(i, paints[i]);
        xyitemrenderer.setSeriesStroke(i, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    }
    plot.setRangeAxis(((AbstractTimeChartStrategy) this.datasetStrategy).getRangeAxis());
    DashDateAxis axisDate = new DashDateAxis();
    axisDate.setDateFormatOverride(
            ((AbstractTimeChartStrategy) this.datasetStrategy).getTimePeriod().getDateFormat());
    axisDate.setLabel(this.datasetStrategy.getXAxisLabel());
    axisDate.setTickUnit(getTickUnit(((AbstractTimeChartStrategy) this.datasetStrategy).getTimePeriod()));
    axisDate.setUpperMargin(0.0D);
    axisDate.setDateTickLabelAngle(-0.6);

    if (((AbstractTimeChartStrategy) this.datasetStrategy).getStartDate() != null
            && ((AbstractTimeChartStrategy) this.datasetStrategy).getEndDate() != null) {
        axisDate.setRangeWithMargins(
                new DateRange(((AbstractTimeChartStrategy) this.datasetStrategy).getStartDate(),
                        ((AbstractTimeChartStrategy) this.datasetStrategy).getEndDate()));

    }
    plot.setDomainAxis(axisDate);

    Date[] dates = DateUtils.getAllDates(((AbstractTimeChartStrategy) this.datasetStrategy).getStartDate(),
            ((AbstractTimeChartStrategy) this.datasetStrategy).getEndDate(),
            ((AbstractTimeChartStrategy) this.datasetStrategy).getTimePeriod());
    int width = (dates.length * ChartUtils.STANDARD_TIME_ENTRY_WIDTH)
            + ChartUtils.STANDARD_TIME_ADDITIONAL_WIDTH;
    if (width > ChartUtils.MINIMUM_WIDTH) {
        this.setWidth(width);
    } else {
        this.setWidth(ChartUtils.MINIMUM_WIDTH);
    }
}

From source file:org.gumtree.vis.awt.time.TimePlotChartEditor.java

@Override
public void updateChart(JFreeChart chart) {
    super.updateChart(chart);
    if (currentDataset != null && currentSeriesIndex >= 0) {
        XYItemRenderer renderer = chart.getXYPlot().getRendererForDataset(currentDataset);
        if (renderer instanceof XYLineAndShapeRenderer) {
            renderer.setSeriesPaint(currentSeriesIndex, curveColorPaint.getPaint());
            Stroke stroke = curveStrokeSample.getStroke();
            if (stroke == null) {
                ((XYLineAndShapeRenderer) renderer).setSeriesLinesVisible(currentSeriesIndex, false);
            } else {
                ((XYLineAndShapeRenderer) renderer).setSeriesLinesVisible(currentSeriesIndex, true);
                renderer.setSeriesStroke(currentSeriesIndex, stroke);
            }/*from w w w  . j av  a 2 s .c om*/

            //             if (!isMarkerVisible) {
            //                for (int i = 0; i < chart.getXYPlot().getSeriesCount(); i++) {
            //                   ((XYLineAndShapeRenderer) renderer).setSeriesShapesVisible(i, 
            //                         isMarkerVisible);
            //                }
            //             }
            //             ((XYLineAndShapeRenderer) renderer).setBaseShapesVisible(
            //                   isMarkerVisible);

            ((XYLineAndShapeRenderer) renderer).setSeriesShapesVisible(currentSeriesIndex,
                    showMarker.isSelected());

            Shape shape = currentShape.getShape();
            if (shape == null) {
                ((XYLineAndShapeRenderer) renderer).setSeriesShapesVisible(currentSeriesIndex, false);
            } else {
                //                ((XYLineAndShapeRenderer) renderer).setSeriesShapesVisible(
                //                      currentSeriesIndex,  true);
                renderer.setSeriesShape(currentSeriesIndex, shape);
            }

            ((XYLineAndShapeRenderer) renderer).setSeriesShapesFilled(currentSeriesIndex,
                    markerFilled.isSelected());

            renderer.setSeriesVisible(currentSeriesIndex, curveVisable.isSelected());

            //Update logarithm X filed
            ValueAxis axis = chart.getXYPlot().getDomainAxis();
            if (showAllHistory.isSelected()) {
                axis.setFixedAutoRange(0d);
            }
            if (showPartHistory.isSelected()) {
                double fixedTimeSec = 0;
                try {
                    fixedTimeSec = Double.valueOf(timeField.getText());
                } catch (Exception e) {
                    // TODO: handle exception
                }
                if (fixedTimeSec <= 0) {
                    fixedTimeSec = 60;
                }
                axis.setFixedAutoRange(fixedTimeSec * 1000);
            }

            //Update logarithm Y filed
            axis = chart.getXYPlot().getRangeAxis();
            if (axis instanceof LogarithmizableAxis) {
                //                if (logarithmY.isSelected() != initialLogarithmY) {
                //                   ((LogarithmizableAxis) axis).setLogarithmic(
                //                         logarithmY.isSelected());
                //                   ((LogarithmizableAxis) axis).autoAdjustRange();
                //                }
            }

        }
    }
}

From source file:net.nikr.eve.jeveasset.gui.tabs.tracker.TrackerTab.java

private void updateRender(int index, Color color) {
    XYItemRenderer renderer = jNextChart.getXYPlot().getRenderer();
    renderer.setSeriesPaint(index, color);
    renderer.setSeriesStroke(index, new BasicStroke(1));
}

From source file:org.optaplanner.benchmark.impl.statistic.memoryuse.MemoryUseProblemStatistic.java

@Override
public void writeGraphFiles(BenchmarkReport benchmarkReport) {
    Locale locale = benchmarkReport.getLocale();
    NumberAxis xAxis = new NumberAxis("Time spent");
    xAxis.setNumberFormatOverride(new MillisecondsSpentNumberFormat(locale));
    NumberAxis yAxis = new NumberAxis("Memory");
    yAxis.setNumberFormatOverride(NumberFormat.getInstance(locale));
    XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
    plot.setOrientation(PlotOrientation.VERTICAL);
    int seriesIndex = 0;
    for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) {
        XYSeries usedSeries = new XYSeries(
                singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix() + " used");
        // TODO enable max memory, but in the same color as used memory, but with a dotted line instead
        //            XYSeries maxSeries = new XYSeries(
        //                    singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix() + " max");
        XYItemRenderer renderer = new XYLineAndShapeRenderer();
        if (singleBenchmarkResult.isSuccess()) {
            MemoryUseSingleStatistic singleStatistic = (MemoryUseSingleStatistic) singleBenchmarkResult
                    .getSingleStatistic(problemStatisticType);
            for (MemoryUseStatisticPoint point : singleStatistic.getPointList()) {
                long timeMillisSpent = point.getTimeMillisSpent();
                MemoryUseMeasurement memoryUseMeasurement = point.getMemoryUseMeasurement();
                usedSeries.add(timeMillisSpent, memoryUseMeasurement.getUsedMemory());
                //                    maxSeries.add(timeMillisSpent, memoryUseMeasurement.getMaxMemory());
            }//from   w w w . j  a  v  a  2  s . c  o  m
        }
        XYSeriesCollection seriesCollection = new XYSeriesCollection();
        seriesCollection.addSeries(usedSeries);
        //            seriesCollection.addSeries(maxSeries);
        plot.setDataset(seriesIndex, seriesCollection);

        if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) {
            // Make the favorite more obvious
            renderer.setSeriesStroke(0, new BasicStroke(2.0f));
            //                renderer.setSeriesStroke(1, new BasicStroke(2.0f));
        }
        plot.setRenderer(seriesIndex, renderer);
        seriesIndex++;
    }
    JFreeChart chart = new JFreeChart(problemBenchmarkResult.getName() + " memory use statistic",
            JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    graphFile = writeChartToImageFile(chart, problemBenchmarkResult.getName() + "MemoryUseStatistic");
}

From source file:windows.sensorWindow.java

/**
 * updates the width of the template plot
 * /*from www  .  ja v a  2s. co m*/
 * @param UID
 */
public static void updateTmplPlotWidth(String UID, int index) {
    Brick tmpBrick = Brick.getBrick(connectionData.BrickList, UID);
    if (index == 0) {
        if (rendererMap3.containsKey(UID)) {
            XYItemRenderer rendererTmp = rendererMap3.get(UID);
            int width = computeTmplPlotWidth(tmpBrick.tmpl1Width);
            BasicStroke stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL);// ,
            // 10.0f,
            // dash,
            // 0.0f);
            rendererTmp.setSeriesPaint(0, Color.GREEN);
            // renderer3.setSeriesStroke( 0, new BasicStroke( 1 ) );
            rendererTmp.setSeriesStroke(0, stroke);
            rendererMap3.put(UID, rendererTmp);
            // tmplPlot1Width.put(UID,
            // computeTmplPlotWidth(tmpBrick.tmpl1Width));
        }
    }
    if (index == 1) {
        if (rendererMap4.containsKey(UID)) {
            // TODO
        }
    }
}

From source file:windows.sensorWindow.java

/**
 * creates all relevant data and adds it into the corresponding maps
 * //from w  ww . j  a  v  a  2  s. c  o  m
 * @param UID
 *            UID of the plotting sensor
 */
@SuppressWarnings("deprecation")
public static void addPlot(Brick newBrick) {
    // create series
    TimeSeries newSeries = new TimeSeries("" + 0, Millisecond.class);
    TimeSeries newSeries2 = new TimeSeries("" + 0, Millisecond.class);
    TimeSeries newSeries3 = new TimeSeries("" + 0, Millisecond.class);
    TimeSeries newSeries4 = new TimeSeries("" + 0, Millisecond.class);
    TimeSeries newSeries5 = new TimeSeries("" + 0, Millisecond.class);
    TimeSeries newSeries6 = new TimeSeries("" + 0, Millisecond.class);

    Measurement m1 = new Measurement(maxValues, maxCycles, newBrick.uid, 0);
    valuesMap.put(newBrick.uid, m1);
    if (newBrick.checked3 == true) {
        Measurement m2 = new Measurement(maxValues, maxCycles, newBrick.uid, 1);
        values2Map.put(newBrick.uid, m2);
    }

    // create entry in state map
    plot1StateMap.put(newBrick.uid, 0);
    plot2StateMap.put(newBrick.uid, 0);

    // create index map entry
    tmplindex.put(newBrick.uid, 0);

    // create avrgCtrlEnabled maps
    if (newBrick.controlAverage == true)
        avrgCtrl1Enabled.put(newBrick.uid, true);
    else
        avrgCtrl1Enabled.put(newBrick.uid, false);
    if (newBrick.controlAverage2 == true)
        avrgCtrl2Enabled.put(newBrick.uid, true);
    else
        avrgCtrl2Enabled.put(newBrick.uid, false);

    // create series map entry
    seriesMap.put(newBrick.uid, newSeries);
    seriesMap2.put(newBrick.uid, newSeries2);
    seriesMap3.put(newBrick.uid, newSeries3);
    seriesMap4.put(newBrick.uid, newSeries4);
    seriesMap5.put(newBrick.uid, newSeries3);
    seriesMap6.put(newBrick.uid, newSeries4);

    // create collection map entry
    seriesCollectionMap.put(newBrick.uid, new TimeSeriesCollection(newSeries));
    seriesCollectionMap2.put(newBrick.uid, new TimeSeriesCollection(newSeries2));
    tmplCollection1_1.put(newBrick.uid, new TimeSeriesCollection(newSeries3));
    tmplCollection1_2.put(newBrick.uid, new TimeSeriesCollection(newSeries4));
    tmplCollection2_1.put(newBrick.uid, new TimeSeriesCollection(newSeries5));
    tmplCollection2_2.put(newBrick.uid, new TimeSeriesCollection(newSeries6));

    // create plot map entry, special case for current/voltage brick, since
    // it has 2 parallel measurements and therefore 2 graphs must be treated
    XYPlot tmpSubPlot;
    tmpSubPlot = new XYPlot(seriesCollectionMap.get(newBrick.uid), null, null, new StandardXYItemRenderer());

    // create the 1st graph
    if (newBrick.checked2 == true) {
        // create plot map entry
        NumberAxis rangeAxis = new NumberAxis(
                String.valueOf(constants.brickUnitMap.get(newBrick.deviceIdentifier)));
        rangeAxis.setAutoRangeIncludesZero(true);
        tmpSubPlot.setRangeAxis(0, rangeAxis);
        rangeAxis.setLabelPaint(Color.BLUE);
        rangeAxis.setVisible(newBrick.checked2);
        tmpSubPlot.setDataset(0, seriesCollectionMap.get(newBrick.uid));

        // set dot - shape
        // Shape cross = ShapeUtilities.createDiagonalCross(3, 1);

        // create and store renderer
        XYItemRenderer renderer1 = new XYLineAndShapeRenderer();
        renderer1 = tmpSubPlot.getRenderer();
        renderer1.setSeriesPaint(0, Color.BLUE);
        renderer1.setSeriesStroke(0, new BasicStroke(3));
        // line = dashes:
        // float dash[] = {5.0f};
        // renderer1.setSeriesStroke( 0, new
        // BasicStroke(3,BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
        // 10.0f, dash, 0.0f));
        // renderer1.setSeriesShape(0, cross);
        tmpSubPlot.setRenderer(0, renderer1);

        // set colors
        tmpSubPlot.setBackgroundPaint(Color.white);
        tmpSubPlot.setDomainGridlinePaint(Color.lightGray);
        tmpSubPlot.setRangeGridlinePaint(Color.lightGray);
        // tmpSubPlot.setRenderer(renderer2);

        // set font
        rangeAxis.setLabelFont(customFonts.get("axisLabelFont"));
        rangeAxis.setTickLabelFont(customFonts.get("axisValueFont"));

        // create template graph
        // if (newBrick.ctrlTmpl[0] == true)
        // {
        tmpSubPlot.setDataset(2, tmplCollection1_1.get(newBrick.uid));

        XYItemRenderer renderer3 = new XYLineAndShapeRenderer();
        int width = computeTmplPlotWidth(newBrick.tmpl1Width);
        BasicStroke stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND);// , 10.0f, dash, 0.0f);
        renderer3.setSeriesPaint(0, Color.GREEN);
        // renderer3.setSeriesStroke( 0, new BasicStroke( 1 ) );
        renderer3.setSeriesStroke(0, stroke);
        renderer3.setSeriesVisible(0, newBrick.ctrlTmpl[0]);
        rendererMap3.put(newBrick.uid, renderer3);
        tmpSubPlot.setRenderer(2, rendererMap3.get(newBrick.uid));
        // }

        // put everything to the maps
        rendererMap.put(newBrick.uid, renderer1);
        plotMap.put(newBrick.uid, tmpSubPlot);
        axisMap.put(newBrick.uid, rangeAxis);
    }

    // create the 2nd graph
    if (newBrick.checked3 == true) {
        // set second axis for voltage/ampere brick
        NumberAxis secondaryAxis = new NumberAxis(
                String.valueOf(constants.brick2ndUnitMap.get(newBrick.deviceIdentifier)));
        secondaryAxis.setAutoRangeIncludesZero(true);
        tmpSubPlot.setRangeAxis(1, secondaryAxis);
        secondaryAxis.setLabelPaint(Color.RED);
        secondaryAxis.setVisible(newBrick.checked3);
        tmpSubPlot.setDataset(1, seriesCollectionMap2.get(newBrick.uid));
        tmpSubPlot.mapDatasetToRangeAxis(1, 1);

        // set font
        secondaryAxis.setLabelFont(customFonts.get("axisLabelFont"));
        secondaryAxis.setTickLabelFont(customFonts.get("axisValueFont"));

        // create and store renderer
        XYItemRenderer renderer2 = new StandardXYItemRenderer();
        // renderer2 = tmpSubPlot.getRenderer();
        renderer2.setSeriesPaint(1, Color.RED);
        renderer2.setSeriesStroke(0, new BasicStroke(3));
        tmpSubPlot.setRenderer(1, renderer2);

        // set colors
        tmpSubPlot.setBackgroundPaint(Color.white);
        tmpSubPlot.setDomainGridlinePaint(Color.lightGray);
        tmpSubPlot.setRangeGridlinePaint(Color.lightGray);

        // ----------------------------------------------------------------------------------
        // create min1 critical map value
        ValueMarker vm5 = new ValueMarker(newBrick.tresholdMin2);
        markerMapMin2Critical.put(newBrick.uid, vm5);
        // set critical line
        markerMapMin2Critical.get(newBrick.uid).setPaint(Color.red);
        markerMapMin2Critical.get(newBrick.uid).setLabel(
                String.valueOf(constants.brick2ndUnitMap.get(newBrick.deviceIdentifier)) + " critical min");
        markerMapMin2Critical.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        markerMapMin2Critical.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        tmpSubPlot.addRangeMarker(1, markerMapMin2Critical.get(newBrick.uid), Layer.BACKGROUND);

        // create min1 warning map value
        ValueMarker vm6 = new ValueMarker(
                newBrick.tresholdMin2 + newBrick.tresholdMin2 * warningPercentage / 100);
        markerMapMin2Warning.put(newBrick.uid, vm6);
        // set warning line
        markerMapMin2Warning.get(newBrick.uid).setPaint(Color.orange);
        markerMapMin2Warning.get(newBrick.uid).setLabel(
                String.valueOf(constants.brick2ndUnitMap.get(newBrick.deviceIdentifier)) + " warning min");
        markerMapMin2Warning.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        markerMapMin2Warning.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        // tmpSubPlot.addRangeMarker(markerMapMin2Warning.get(newBrick.uid));
        tmpSubPlot.addRangeMarker(1, markerMapMin2Warning.get(newBrick.uid), Layer.BACKGROUND);

        // create max1 critical map value
        ValueMarker vm7 = new ValueMarker(newBrick.tresholdMax2);
        markerMapMax2Critical.put(newBrick.uid, vm7);
        // set critical line
        markerMapMax2Critical.get(newBrick.uid).setPaint(Color.red);
        markerMapMax2Critical.get(newBrick.uid).setLabel(
                String.valueOf(constants.brick2ndUnitMap.get(newBrick.deviceIdentifier)) + " critical max");
        markerMapMax2Critical.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        markerMapMax2Critical.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        tmpSubPlot.addRangeMarker(1, markerMapMax2Critical.get(newBrick.uid), Layer.BACKGROUND);

        // create max1 warning map value
        ValueMarker vm8 = new ValueMarker(
                newBrick.tresholdMax2 + newBrick.tresholdMax2 * warningPercentage / 100);
        markerMapMax2Warning.put(newBrick.uid, vm8);
        // set warning line
        markerMapMax2Warning.get(newBrick.uid).setPaint(Color.orange);
        markerMapMax2Warning.get(newBrick.uid).setLabel(
                String.valueOf(constants.brick2ndUnitMap.get(newBrick.deviceIdentifier)) + " warning max");
        markerMapMax2Warning.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        markerMapMax2Warning.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        tmpSubPlot.addRangeMarker(1, markerMapMax2Warning.get(newBrick.uid), Layer.BACKGROUND);

        // create and add min, max and average markers
        // create maxima marker
        ValueMarker vmMax = new ValueMarker(0);
        vmMax.setPaint(Color.orange);
        vmMax.setLabel("max");
        vmMax.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        vmMax.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        // create minima marker
        ValueMarker vmMin = new ValueMarker(0);
        vmMin.setPaint(Color.orange);
        vmMin.setLabel("min");
        vmMin.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        vmMin.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        // create average marker
        ValueMarker vmAvg = new ValueMarker(0);
        vmAvg.setPaint(Color.red);
        vmAvg.setLabel("average");
        vmAvg.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        vmAvg.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        // add to maps
        marker2Maxima.put(newBrick.uid, vmMax);
        marker2Minima.put(newBrick.uid, vmMin);
        marker2Average.put(newBrick.uid, vmAvg);
        // add to plot
        tmpSubPlot.addRangeMarker(1, vmMax, Layer.BACKGROUND);
        tmpSubPlot.addRangeMarker(1, vmMin, Layer.BACKGROUND);
        tmpSubPlot.addRangeMarker(1, vmAvg, Layer.BACKGROUND);

        // create and add avrgCntrMarkers
        // create upper marker
        ValueMarker avrgCtrl2high = new ValueMarker(newBrick.getAvg2high());
        avrgCtrl2high.setPaint(Color.orange);
        avrgCtrl2high.setLabel("avrg high");
        avrgCtrl2high.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        avrgCtrl2high.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        // create lower marker
        ValueMarker avrgCtrl2low = new ValueMarker(newBrick.getAvg2low());
        avrgCtrl2low.setPaint(Color.orange);
        avrgCtrl2low.setLabel("avrg low");
        avrgCtrl2low.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        avrgCtrl2low.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        // add both markers
        avrg2High.put(newBrick.uid, avrgCtrl2high);
        avrg2Low.put(newBrick.uid, avrgCtrl2low);
        // add both to plot
        if (newBrick.controlAverage2) {
            tmpSubPlot.addRangeMarker(1, avrgCtrl2high, Layer.BACKGROUND);
            tmpSubPlot.addRangeMarker(1, avrgCtrl2low, Layer.BACKGROUND);
        }
        // ----------------------------------------------------------------------------------

        // put everything to the map
        rendererMap2.put(newBrick.uid, renderer2);
        plotMap.put(newBrick.uid, tmpSubPlot);
        axisMap2.put(newBrick.uid, secondaryAxis);
    }

    // 1st graph
    // markers--------------------------------------------------------------------------------------------------
    // create min1 critical map value
    ValueMarker vm1 = new ValueMarker(newBrick.tresholdMin1);
    markerMapMin1Critical.put(newBrick.uid, vm1);
    // set critical line
    markerMapMin1Critical.get(newBrick.uid).setPaint(Color.red);
    // / .setLabel("critical");
    // markerMapMin1Critical.get(newBrick.uid).setLabelAnchor(RectangleAnchor.BOTTOM);
    markerMapMin1Critical.get(newBrick.uid)
            .setLabel(String.valueOf(constants.brickUnitMap.get(newBrick.deviceIdentifier)) + " critical min");
    markerMapMin1Critical.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_LEFT);
    markerMapMin1Critical.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_LEFT);
    plotMap.get(newBrick.uid).addRangeMarker(markerMapMin1Critical.get(newBrick.uid));

    // create min1 warning map value
    ValueMarker vm2 = new ValueMarker(newBrick.tresholdMin1 + newBrick.tresholdMin1 * warningPercentage / 100);
    markerMapMin1Warning.put(newBrick.uid, vm2);
    // set warning line
    markerMapMin1Warning.get(newBrick.uid).setPaint(Color.orange);
    // marker2Map.get(newBrick.uid).setPaint(Color.);
    // / marker2Map.get(newBrick.uid).setLabel("warning");
    markerMapMin1Warning.get(newBrick.uid)
            .setLabel(String.valueOf(constants.brickUnitMap.get(newBrick.deviceIdentifier)) + " warning min");
    markerMapMin1Warning.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_LEFT);
    markerMapMin1Warning.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_LEFT);
    plotMap.get(newBrick.uid).addRangeMarker(markerMapMin1Warning.get(newBrick.uid));

    // create max1 critical map value
    ValueMarker vm3 = new ValueMarker(newBrick.tresholdMax1);
    markerMapMax1Critical.put(newBrick.uid, vm3);
    // set critical line
    markerMapMax1Critical.get(newBrick.uid).setPaint(Color.red);
    // / .setLabel("critical");
    // markerMapMax1Critical.get(newBrick.uid).setLabelAnchor(RectangleAnchor.BOTTOM);
    markerMapMax1Critical.get(newBrick.uid)
            .setLabel(String.valueOf(constants.brickUnitMap.get(newBrick.deviceIdentifier)) + " critical max");
    markerMapMax1Critical.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_LEFT);
    markerMapMax1Critical.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_LEFT);
    plotMap.get(newBrick.uid).addRangeMarker(markerMapMax1Critical.get(newBrick.uid));

    // create max1 warning map value
    ValueMarker vm4 = new ValueMarker(newBrick.tresholdMax1 + newBrick.tresholdMax1 * warningPercentage / 100);
    markerMapMax1Warning.put(newBrick.uid, vm4);
    // set warning line
    markerMapMax1Warning.get(newBrick.uid).setPaint(Color.orange);
    markerMapMax1Warning.get(newBrick.uid)
            .setLabel(String.valueOf(constants.brickUnitMap.get(newBrick.deviceIdentifier)) + " warning max");
    markerMapMax1Warning.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_LEFT);
    markerMapMax1Warning.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_LEFT);
    plotMap.get(newBrick.uid).addRangeMarker(markerMapMax1Warning.get(newBrick.uid));

    // create and add min, max and average markers
    // create maxima marker
    ValueMarker vmMax = new ValueMarker(0);
    vmMax.setPaint(Color.cyan);
    vmMax.setLabel("max");
    vmMax.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    vmMax.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    // create minima marker
    ValueMarker vmMin = new ValueMarker(0);
    vmMin.setPaint(Color.cyan);
    vmMin.setLabel("min");
    vmMin.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    vmMin.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    // create average marker
    ValueMarker vmAvg = new ValueMarker(0);
    vmAvg.setPaint(Color.blue);
    vmAvg.setLabel("average");
    vmAvg.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    vmAvg.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    // add to maps
    markerMaxima.put(newBrick.uid, vmMax);
    markerMinima.put(newBrick.uid, vmMin);
    markerAverage.put(newBrick.uid, vmAvg);
    // add to plot
    plotMap.get(newBrick.uid).addRangeMarker(vmMax);
    plotMap.get(newBrick.uid).addRangeMarker(vmMin);
    plotMap.get(newBrick.uid).addRangeMarker(vmAvg);

    // create and add avrgCntrMarkers
    // create upper marker
    ValueMarker avrgCtrl1high = new ValueMarker(newBrick.getAvg1high());
    avrgCtrl1high.setPaint(Color.orange);
    avrgCtrl1high.setLabel("avrg high");
    avrgCtrl1high.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    avrgCtrl1high.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    // create lower marker
    ValueMarker avrgCtrl1low = new ValueMarker(newBrick.getAvg1low());
    avrgCtrl1low.setPaint(Color.orange);
    avrgCtrl1low.setLabel("avrg low");
    avrgCtrl1low.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    avrgCtrl1low.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    // add both markers
    avrg1High.put(newBrick.uid, avrgCtrl1high);
    avrg1Low.put(newBrick.uid, avrgCtrl1low);
    // add both to plot
    if (newBrick.controlAverage) {
        plotMap.get(newBrick.uid).addRangeMarker(avrgCtrl1high);
        plotMap.get(newBrick.uid).addRangeMarker(avrgCtrl1low);
    }
    // -----------------------------------------------------------------------------------------------------

    // set title
    NumberAxis axisForTitleOnly = new NumberAxis(
            data.constants.brickIdMap.get(newBrick.deviceIdentifier) + " (" + newBrick.uid + ")");
    axisForTitleOnly.setLabelFont(customFonts.get("titleFont"));
    axisForTitleOnly.setTickLabelsVisible(false);
    axisForTitleOnly.setTickMarksVisible(false);
    axisForTitleOnly.setMinorTickMarksVisible(false);
    axisForTitleOnly.setAxisLineVisible(false);
    plotMap.get(newBrick.uid).setDomainAxis(1, axisForTitleOnly);

    // add subplot to the main plot
    plot.add(plotMap.get(newBrick.uid));
}

From source file:mil.tatrc.physiology.utilities.csv.plots.ActionEventPlotter.java

public void createGraph(PlotJob job, List<List<Double>> timeData, List<List<Double>> data,
        List<LogEvent> events, List<SEAction> actions) {
    CSVPlotTool plotTool = new CSVPlotTool(); //to leverage existing functions
    String title = job.name + "_";
    XYSeriesCollection dataSet = new XYSeriesCollection();
    double maxY = 0;
    double minY = Double.MAX_VALUE;
    for (int i = 0; i < timeData.size(); i++) {
        if (timeData.get(i) == null || data.get(i) == null) {
            job.bgColor = Color.white; //This hits when we have Expected data but NOT computed data
            continue;
        }/*w w  w .j a v a  2 s .  com*/

        title = title + job.headers.get(i) + "_";
        XYSeries dataSeries;
        if (job.isComparePlot) {
            if (timeData.size() > 1)
                dataSeries = plotTool.createXYSeries(i == 0 ? "Expected" : "Computed", timeData.get(i),
                        data.get(i));
            else //If we're comparing but only have one data list, expected is missing, so rename to computed
            {
                dataSeries = plotTool.createXYSeries("Computed", timeData.get(i), data.get(i));
            }
        } else
            dataSeries = plotTool.createXYSeries(job.headers.get(i), timeData.get(i), data.get(i));
        dataSet.addSeries(dataSeries);
        maxY = maxY < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY;
        minY = minY > dataSeries.getMinY() ? dataSeries.getMinY() : minY;
    }
    title = title + "vs_Time_Action_Event_Plot";

    //Override the constructed title if desired (usually for compare plots)
    if (job.titleOverride != null && !job.titleOverride.isEmpty()
            && !job.titleOverride.equalsIgnoreCase("None"))
        title = job.titleOverride;

    double rangeLength = maxY - minY;
    if (Math.abs(rangeLength) < 1e-6) {
        rangeLength = .01;
    }

    class AEEntry implements Comparable<AEEntry> {
        public String name;
        public List<Double> times = new ArrayList<Double>();
        public List<Double> YVals = new ArrayList<Double>();
        public String type = "";

        public int compareTo(AEEntry entry) {
            return times.get(0) < entry.times.get(0) ? -1 : times.get(0) > entry.times.get(0) ? 1 : 0;
        }
    }

    List<AEEntry> allActionsAndEvents = new ArrayList<AEEntry>();

    if (!job.skipAllEvents) {
        //Make points for each event
        //Treat each event like two points on the same vertical line
        for (LogEvent event : events) {
            boolean skip = false;

            for (String eventToSkip : job.eventOmissions) {
                if (event.text.contains(eventToSkip))
                    skip = true;
            }
            if (skip)
                continue;
            AEEntry entry = new AEEntry();

            entry.times.add(event.time.getValue());
            if (job.logAxis)
                entry.YVals.add(maxY);
            else if (job.forceZeroYAxisBound && maxY < 0)
                entry.YVals.add(-.01);
            else
                entry.YVals.add(maxY + 0.15 * rangeLength);

            entry.times.add(event.time.getValue());
            if (job.logAxis)
                entry.YVals.add(minY);
            else if (job.forceZeroYAxisBound && minY > 0)
                entry.YVals.add(-.01);
            else
                entry.YVals.add(minY - 0.15 * rangeLength);

            entry.name = event.text + "\r\nt=" + event.time.getValue();
            entry.type = "EVENT:";

            allActionsAndEvents.add(entry);
        }
    }

    if (!job.skipAllActions) {
        //Make similar entries for actions
        for (SEAction action : actions) {
            boolean skip = false;

            for (String actionToSkip : job.actionOmissions) {
                if (action.toString().contains(actionToSkip))
                    skip = true;
            }
            if (skip)
                continue;

            if (action.toString().contains("Advance Time"))
                continue;

            AEEntry entry = new AEEntry();

            entry.times.add(action.getScenarioTime().getValue());
            if (job.logAxis)
                entry.YVals.add(maxY);
            else if (job.forceZeroYAxisBound && maxY < 0)
                entry.YVals.add(-.01);
            else
                entry.YVals.add(maxY + 0.15 * rangeLength);

            entry.times.add(action.getScenarioTime().getValue());
            if (job.logAxis)
                entry.YVals.add(minY);
            else if (job.forceZeroYAxisBound && minY > 0)
                entry.YVals.add(-.01);
            else
                entry.YVals.add(minY - 0.15 * rangeLength);

            entry.name = action.toString() + "\r\nt=" + action.getScenarioTime().getValue();
            entry.type = "ACTION:";

            allActionsAndEvents.add(entry);
        }
    }

    //Sort the list
    Collections.sort(allActionsAndEvents);

    //Add a series for each entry
    for (AEEntry entry : allActionsAndEvents) {
        dataSet.addSeries(plotTool.createXYSeries(entry.type + entry.name, entry.times, entry.YVals));
    }

    //If we have experimental data, try to load it and create a dataset for it
    XYSeriesCollection expDataSet = new XYSeriesCollection();
    if (job.experimentalData != null && !job.experimentalData.isEmpty()) {
        Map<String, List<Double>> expData = new HashMap<String, List<Double>>();
        List<String> expHeaders = new ArrayList<String>();

        try {
            CSVContents csv = new CSVContents(job.experimentalData);
            csv.abbreviateContents = 0;
            csv.readAll(expData);
            expHeaders = csv.getHeaders();
        } catch (Exception e) {
            Log.error("Unable to read experimental data");
        }

        if (!expData.isEmpty() && !expHeaders.isEmpty()) {
            List<Double> expTimeData = new ArrayList<Double>();
            expTimeData = expData.get("Time(s)");

            for (String h : expHeaders) //Will assume all headers from exp file will be on same Y axis vs time
            {
                if (h.equalsIgnoreCase("Time(s)"))
                    continue;

                expDataSet.addSeries(plotTool.createXYSeries("Experimental " + h, expTimeData, expData.get(h)));
            }
        }
    }

    //set labels
    String XAxisLabel = "Time(s)";
    String YAxisLabel = job.headers.get(0);

    JFreeChart chart = ChartFactory.createXYLineChart(
            job.titleOverride != null && job.titleOverride.equalsIgnoreCase("None") ? "" : title, // chart title
            XAxisLabel, // x axis label
            YAxisLabel, // y axis label
            dataSet, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    Log.info("Creating Graph " + title);
    XYPlot plot = (XYPlot) chart.getPlot();

    if (!job.logAxis) {
        // Determine Y range
        double resMax0 = maxY;
        double resMin0 = minY;
        if (Double.isNaN(resMax0) || Double.isNaN(resMin0))
            plot.getDomainAxis().setLabel("Range is NaN");
        if (DoubleUtils.isZero(resMin0))
            resMin0 = -0.000001;
        if (DoubleUtils.isZero(resMax0))
            resMax0 = 0.000001;
        if (job.forceZeroYAxisBound && resMin0 >= 0)
            resMin0 = -.000001;
        if (job.forceZeroYAxisBound && resMax0 <= 0)
            resMax0 = .000001;
        rangeLength = resMax0 - resMin0;
        ValueAxis yAxis = plot.getRangeAxis();
        if (rangeLength != 0)
            yAxis.setRange(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength);//15% buffer so we can see top and bottom clearly           

        //Add another Y axis to the right side for easier reading
        ValueAxis rightYAxis = new NumberAxis();
        rightYAxis.setRange(yAxis.getRange());
        rightYAxis.setLabel("");

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null) {
                yAxis.setLowerBound(job.Y1LowerBound);
                rightYAxis.setLowerBound(job.Y1LowerBound);
            }
            if (job.Y1UpperBound != null) {
                yAxis.setUpperBound(job.Y1UpperBound);
                rightYAxis.setUpperBound(job.Y1UpperBound);
            }
        } catch (Exception e) {
            Log.error(
                    "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
        }
        plot.setRangeAxis(0, yAxis);
        plot.setRangeAxis(1, rightYAxis);

    } else {
        double resMin = minY;
        double resMax = maxY;
        if (resMin <= 0.0)
            resMin = .00001;
        LogarithmicAxis yAxis = new LogarithmicAxis("Log(" + YAxisLabel + ")");
        LogarithmicAxis rightYAxis = new LogarithmicAxis("");
        yAxis.setLowerBound(resMin);
        rightYAxis.setLowerBound(resMin);
        yAxis.setUpperBound(resMax);
        rightYAxis.setUpperBound(resMax);

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null) {
                yAxis.setLowerBound(job.Y1LowerBound);
                rightYAxis.setLowerBound(job.Y1LowerBound);
            }
            if (job.Y1UpperBound != null) {
                yAxis.setUpperBound(job.Y1UpperBound);
                rightYAxis.setUpperBound(job.Y1UpperBound);
            }
        } catch (Exception e) {
            Log.error(
                    "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
        }
        plot.setRangeAxis(0, yAxis);
        plot.setRangeAxis(1, rightYAxis);
    }

    //Override X bounds if desired
    try {
        if (job.X1LowerBound != null)
            plot.getDomainAxis(0).setLowerBound(job.X1LowerBound);
        if (job.X1UpperBound != null)
            plot.getDomainAxis(0).setUpperBound(job.X1UpperBound);
    } catch (Exception e) {
        Log.error("Couldn't set X bounds. You probably tried to set a bound on an axis that doesn't exist.");
    }

    //Override labels if desired
    if (job.X1Label != null && !plot.getDomainAxis(0).getLabel().contains("NaN"))
        plot.getDomainAxis(0).setLabel(job.X1Label.equalsIgnoreCase("None") ? "" : job.X1Label);
    if (job.Y1Label != null)
        plot.getRangeAxis(0).setLabel(job.Y1Label.equalsIgnoreCase("None") ? "" : job.Y1Label);

    //If we have experimental data, set up the renderer for it and add to plot
    if (expDataSet.getSeriesCount() != 0) {
        XYItemRenderer renderer1 = new XYLineAndShapeRenderer(false, true); // Shapes only
        renderer1.setSeriesShape(0, ShapeUtilities.createDiamond(8));
        plot.setDataset(1, expDataSet);
        plot.setRenderer(1, renderer1);
        plot.mapDatasetToDomainAxis(1, 0);
        plot.mapDatasetToRangeAxis(1, 0);
    }

    formatAEPlot(job, chart);
    plot.setDomainGridlinesVisible(job.showGridLines);
    plot.setRangeGridlinesVisible(job.showGridLines);

    //Changing line widths and colors
    XYItemRenderer r = plot.getRenderer();
    BasicStroke wideLine = new BasicStroke(2.0f);
    Color[] AEcolors = { Color.red, Color.green, Color.black, Color.magenta, Color.orange };
    Color[] dataColors = { Color.blue, Color.cyan, Color.gray, Color.black, Color.red };
    for (int i = 0, cIndex = 0; i < dataSet.getSeriesCount(); i++, cIndex++) {
        r.setSeriesStroke(i, wideLine);
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
        renderer.setBaseShapesVisible(false);
        if (cIndex > 4)
            cIndex = 0;
        if (i < job.headers.size()) //Our actual data
        {
            renderer.setSeriesFillPaint(i, dataColors[cIndex]);
            renderer.setSeriesPaint(i, dataColors[cIndex]);
        } else //actions and events in procession of other colors
        {
            renderer.setSeriesFillPaint(i, AEcolors[cIndex]);
            renderer.setSeriesPaint(i, AEcolors[cIndex]);
        }
    }
    //Special color and format changes for compare plots
    if (job.isComparePlot) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();

        for (int i = 0; i < dataSet.getSeriesCount(); i++) {
            if (dataSet.getSeries(i).getKey().toString().equalsIgnoreCase("Expected")) {
                renderer.setSeriesStroke(//makes a dashed line
                        i, //argument below float[]{I,K} -> alternates between solid and opaque (solid for I, opaque for K)
                        new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f,
                                new float[] { 15.0f, 30.0f }, 0.0f));
                renderer.setDrawSeriesLineAsPath(true);
                renderer.setUseFillPaint(true);
                renderer.setBaseShapesVisible(false);
                renderer.setSeriesFillPaint(i, Color.black);
                renderer.setSeriesPaint(i, Color.black);
            }
            if (dataSet.getSeries(i).getKey().toString().equalsIgnoreCase("Computed")) {
                renderer.setSeriesFillPaint(i, Color.red);
                renderer.setSeriesPaint(i, Color.red);
            }
            if (dataSet.getSeries(i).getKey().toString().startsWith("ACTION")) {
                renderer.setSeriesFillPaint(i, Color.green);
                renderer.setSeriesPaint(i, Color.green);
            }
            if (dataSet.getSeries(i).getKey().toString().startsWith("EVENT")) {
                renderer.setSeriesFillPaint(i, Color.blue);
                renderer.setSeriesPaint(i, Color.blue);
            }
        }
    }

    //Split the auto-generated legend into two legends, one for data and one for actions and events
    LegendItemCollection originalLegendCollection = plot.getLegendItems();
    final LegendItemCollection dataLegendCollection = new LegendItemCollection();
    int i;
    for (i = 0; i < job.headers.size() && i < originalLegendCollection.getItemCount(); i++) {
        if (originalLegendCollection.get(i).getLabel().startsWith("ACTION")
                || originalLegendCollection.get(i).getLabel().startsWith("EVENT"))
            break;
        dataLegendCollection.add(originalLegendCollection.get(i));
    }
    final LegendItemCollection remainingLegendCollection = new LegendItemCollection();
    for (; i < originalLegendCollection.getItemCount(); i++) {
        remainingLegendCollection.add(originalLegendCollection.get(i));
    }
    chart.removeLegend();
    LegendItemSource source = new LegendItemSource() {
        LegendItemCollection lic = new LegendItemCollection();
        {
            lic.addAll(dataLegendCollection);
        }

        public LegendItemCollection getLegendItems() {
            return lic;
        }
    };
    LegendTitle dataLegend = new LegendTitle(source);
    dataLegend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));
    dataLegend.setBorder(2, 2, 2, 2);
    dataLegend.setBackgroundPaint(Color.white);
    dataLegend.setPosition(RectangleEdge.TOP);
    dataLegend.setItemFont(new Font("SansSerif", Font.PLAIN, 22));
    chart.addLegend(dataLegend);

    source = new LegendItemSource() {
        LegendItemCollection lic = new LegendItemCollection();
        {
            lic.addAll(remainingLegendCollection);
        }

        public LegendItemCollection getLegendItems() {
            return lic;
        }
    };
    LegendTitle actionEventsLegend = new LegendTitle(source);
    actionEventsLegend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));
    actionEventsLegend.setBorder(2, 2, 2, 2);
    actionEventsLegend.setBackgroundPaint(Color.white);
    actionEventsLegend.setPosition(RectangleEdge.BOTTOM);
    actionEventsLegend.setItemFont(new Font("SansSerif", Font.PLAIN, 22));
    if (!job.hideAELegend && !job.removeAllLegends)
        chart.addLegend(actionEventsLegend);

    if (job.removeAllLegends)
        chart.removeLegend();

    int verticalPixels = 800 + 170 * (allActionsAndEvents.size() / 5);

    //This is a little hacky, but if we want only the legend, just extend Plot() and remove the draw functionality so it makes a blank plot
    class legendPlot extends Plot {
        public void draw(Graphics2D arg0, Rectangle2D arg1, Point2D arg2, PlotState arg3,
                PlotRenderingInfo arg4) {

        }

        public String getPlotType() {
            return null;
        }
    }
    //Then add the legend to that and throw away the original plot
    if (job.legendOnly) {
        chart = new JFreeChart("", null, new legendPlot(), false);
        chart.addLegend(actionEventsLegend);
    }

    try {
        FileUtils.createDirectory(job.outputDir);
        String filename = job.outputFilename == null
                ? job.outputDir + "/" + plotTool.MakeFileName(title) + ".jpg"
                : job.outputDir + "/" + job.outputFilename;
        if (!filename.endsWith(".jpg"))
            filename = filename + ".jpg";
        File JPGFile = new File(filename);
        if (job.imageHeight != null && job.imageWidth != null)
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, job.imageWidth, job.imageHeight);
        else if (!job.hideAELegend && !job.removeAllLegends)
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, verticalPixels);
        else
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, 800);
    } catch (IOException e) {
        Log.error(e.getMessage());
    }
}

From source file:org.optaplanner.benchmark.impl.statistic.movecountperstep.MoveCountPerStepProblemStatistic.java

@Override
public void writeGraphFiles(BenchmarkReport benchmarkReport) {
    Locale locale = benchmarkReport.getLocale();
    NumberAxis xAxis = new NumberAxis("Time spent");
    xAxis.setNumberFormatOverride(new MillisecondsSpentNumberFormat(locale));
    NumberAxis yAxis = new NumberAxis("Accepted/selected moves per step");
    yAxis.setNumberFormatOverride(NumberFormat.getInstance(locale));
    XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
    DrawingSupplier drawingSupplier = new DefaultDrawingSupplier();
    plot.setOrientation(PlotOrientation.VERTICAL);

    int seriesIndex = 0;
    for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) {
        XYSeries acceptedSeries = new XYSeries(
                singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix() + " accepted");
        XYSeries selectedSeries = new XYSeries(
                singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix() + " selected");
        XYItemRenderer renderer = new XYLineAndShapeRenderer(true, false);
        if (singleBenchmarkResult.isSuccess()) {
            MoveCountPerStepSingleStatistic singleStatistic = (MoveCountPerStepSingleStatistic) singleBenchmarkResult
                    .getSingleStatistic(problemStatisticType);
            for (MoveCountPerStepStatisticPoint point : singleStatistic.getPointList()) {
                long timeMillisSpent = point.getTimeMillisSpent();
                long acceptedMoveCount = point.getMoveCountPerStepMeasurement().getAcceptedMoveCount();
                long selectedMoveCount = point.getMoveCountPerStepMeasurement().getSelectedMoveCount();
                acceptedSeries.add(timeMillisSpent, acceptedMoveCount);
                selectedSeries.add(timeMillisSpent, selectedMoveCount);
            }//  ww  w  . j av a 2  s .c  o  m
        }
        XYSeriesCollection seriesCollection = new XYSeriesCollection();
        seriesCollection.addSeries(acceptedSeries);
        seriesCollection.addSeries(selectedSeries);
        plot.setDataset(seriesIndex, seriesCollection);

        if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) {
            // Make the favorite more obvious
            renderer.setSeriesStroke(0, new BasicStroke(2.0f));
            // Dashed line for selected move count
            renderer.setSeriesStroke(1, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
                    1.0f, new float[] { 2.0f, 6.0f }, 0.0f));
        } else {
            // Dashed line for selected move count
            renderer.setSeriesStroke(1, new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
                    1.0f, new float[] { 2.0f, 6.0f }, 0.0f));
        }
        // Render both lines in the same color
        Paint linePaint = drawingSupplier.getNextPaint();
        renderer.setSeriesPaint(0, linePaint);
        renderer.setSeriesPaint(1, linePaint);
        plot.setRenderer(seriesIndex, renderer);
        seriesIndex++;
    }

    JFreeChart chart = new JFreeChart(problemBenchmarkResult.getName() + " move count per step statistic",
            JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    graphFile = writeChartToImageFile(chart, problemBenchmarkResult.getName() + "MoveCountPerStepStatistic");
}

From source file:org.optaplanner.benchmark.impl.statistic.improvingsteppercentage.ImprovingStepPercentageProblemStatistic.java

@Override
protected void writeGraphStatistic() {
    Map<Class<? extends Move>, XYPlot> plots = new HashMap<Class<? extends Move>, XYPlot>();
    int seriesIndex = 0;
    for (SingleBenchmark singleBenchmark : problemBenchmark.getSingleBenchmarkList()) {
        Map<Class<? extends Move>, XYSeries> seriesMap = new HashMap<Class<? extends Move>, XYSeries>();
        // No direct ascending lines between 2 points, but a stepping line instead
        XYItemRenderer renderer = new XYStepRenderer();
        if (singleBenchmark.isSuccess()) {
            ImprovingStepPercentageSingleStatistic singleStatistic = (ImprovingStepPercentageSingleStatistic) singleBenchmark
                    .getSingleStatistic(problemStatisticType);
            for (Map.Entry<Class<? extends Move>, List<ImprovingStepPercentageSingleStatisticPoint>> entry : singleStatistic
                    .getPointLists().entrySet()) {
                Class<? extends Move> moveClass = entry.getKey();
                if (!seriesMap.containsKey(moveClass)) {
                    seriesMap.put(moveClass,
                            new XYSeries(singleBenchmark.getSolverBenchmark().getNameWithFavoriteSuffix()));
                }//from   w  ww.  jav a 2 s  .c  o m
                XYSeries series = seriesMap.get(moveClass);
                for (ImprovingStepPercentageSingleStatisticPoint point : entry.getValue()) {
                    long timeMillisSpend = point.getTimeMillisSpend();
                    double ratio = point.getRatio();
                    series.add(timeMillisSpend, ratio);
                }
            }
        }
        if (singleBenchmark.getSolverBenchmark().isFavorite()) {
            // Make the favorite more obvious
            renderer.setSeriesStroke(0, new BasicStroke(2.0f));
        }
        for (Map.Entry<Class<? extends Move>, XYSeries> entry : seriesMap.entrySet()) {
            Class<? extends Move> moveClass = entry.getKey();
            if (!plots.containsKey(moveClass)) {
                plots.put(moveClass, createPlot(moveClass));
            }
            plots.get(moveClass).setDataset(seriesIndex, new XYSeriesCollection(entry.getValue()));
            plots.get(moveClass).setRenderer(seriesIndex, renderer);
        }
        for (int i = 0; i < seriesMap.size(); i++) {
        }
        seriesIndex++;
    }
    graphStatisticFileMap = new LinkedHashMap<Class<? extends Move>, File>(plots.size());
    for (Map.Entry<Class<? extends Move>, XYPlot> entry : plots.entrySet()) {
        Class<? extends Move> moveClass = entry.getKey();
        JFreeChart chart = new JFreeChart(problemBenchmark.getName() + " improving step percentage "
                + moveClass.getSimpleName() + " statistic", JFreeChart.DEFAULT_TITLE_FONT, entry.getValue(),
                true);
        graphStatisticFileMap.put(moveClass, writeChartToImageFile(chart, problemBenchmark.getName()
                + "ImprovingStepPercentageStatistic-" + moveClass.getCanonicalName()));
    }
}