Example usage for org.jfree.chart ChartUtilities saveChartAsJPEG

List of usage examples for org.jfree.chart ChartUtilities saveChartAsJPEG

Introduction

In this page you can find the example usage for org.jfree.chart ChartUtilities saveChartAsJPEG.

Prototype

public static void saveChartAsJPEG(File file, JFreeChart chart, int width, int height) throws IOException 

Source Link

Document

Saves a chart to a file in JPEG format.

Usage

From source file:grafix.telas.TelaComparativos.java

private void salvarJPEG() {
    JFileChooser chooser = new JFileChooser();
    chooser.setSelectedFile(new File(".jpg"));
    int returnVal = chooser.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        try {/*from w w w  .j  a  va 2 s  .  c  om*/
            ChartUtilities.saveChartAsJPEG(file, chartPanel.getChart(), chartPanel.getWidth(),
                    chartPanel.getHeight());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:skoa.helpers.Graficos.java

private void barras() {
    unificarDatosFicheros();/*  ww  w . j  a v  a 2  s  . co  m*/
    Vector<String> vectorOrdenUnidades = new Vector<String>();
    vectorOrdenUnidades = ordenDeUnidades();
    aplicarDiferencia(vectorOrdenUnidades);
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset = obtenerSerieBarras(vectorOrdenUnidades);
    String unidad = "";
    //for (int i=0;i<vectorOrdenUnidades.size();i++) unidad=unidad+vectorOrdenUnidades.elementAt(i)+", ";
    for (int i = 0; i < vectorOrdenUnidades.size(); i++) {
        if (vectorOrdenUnidades.elementAt(i).indexOf("W") >= 0
                || vectorOrdenUnidades.elementAt(i).indexOf("L") >= 0
                || vectorOrdenUnidades.elementAt(i).indexOf("m") >= 0
                || vectorOrdenUnidades.elementAt(i).indexOf("B") >= 0)
            unidad = unidad + vectorOrdenUnidades.elementAt(i) + ", ";
        else if (vectorOrdenUnidades.elementAt(i).indexOf("C") >= 0)
            unidad = unidad + "C, ";
        else
            unidad = unidad + ", ";
    }
    unidad = unidad.substring(0, unidad.length() - 2); //Quita el ultimo espacio y la ultima coma.

    JFreeChart grafica = ChartFactory.createBarChart("Valores medidos de las direcciones de grupo", "Fechas", //titulo eje x
            "Mediciones (" + unidad + ")", dataset, PlotOrientation.VERTICAL, true, //leyenda
            true, false);
    if (fechaInicial.isEmpty()) {
        fechaInicial = fechaFinal = "?";
    }
    TextTitle t = new TextTitle("desde " + fechaInicial + " hasta " + fechaFinal,
            new Font("SanSerif", Font.ITALIC, 12));
    grafica.addSubtitle(t);
    CategoryPlot plot = grafica.getCategoryPlot();
    //Modificar eje X
    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
    domainAxis.setTickLabelFont(new Font("Dialog", Font.PLAIN, 8)); //Letra de las fechas ms pequea
    //Esconder las sombras de las barras del barchart.
    CategoryPlot categoryPlot = (CategoryPlot) grafica.getPlot();
    BarRenderer renderer = new BarRenderer();
    renderer.setShadowVisible(false);
    categoryPlot.setRenderer(renderer);
    //-------------------------------------------------
    try {
        ChartUtilities.saveChartAsJPEG(new File(ruta + "BarrasSmall.jpg"), grafica, 400, 300);
        ChartUtilities.saveChartAsJPEG(new File(ruta + "BarrasBig.jpg"), grafica, 900, 600);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }
}

From source file:com.sun.japex.ChartGenerator.java

private int generateTestCaseBarCharts(String baseName, String extension) {
    int nOfFiles = 0;
    List<DriverImpl> driverInfoList = _testSuite.getDriverInfoList();

    // Get number of tests from first driver
    final int nOfTests = driverInfoList.get(0).getAggregateTestCases().size();

    int groupSizesIndex = 0;
    int[] groupSizes = calculateGroupSizes(nOfTests, _plotGroupSize);

    try {//w ww  .  j  a v  a 2  s.co m
        String resultUnit = _testSuite.getParam(Constants.RESULT_UNIT);
        String resultUnitX = _testSuite.getParam(Constants.RESULT_UNIT_X);

        // Ensure japex.resultUnitX is not null
        if (resultUnitX == null) {
            resultUnitX = "";
        }

        // Find first normalizer driver (if any)
        DriverImpl normalizerDriver = null;
        for (DriverImpl di : driverInfoList) {
            if (di.isNormal()) {
                normalizerDriver = di;
                break;
            }
        }

        // Check if normalizer driver can be used as such
        if (normalizerDriver != null) {
            if (normalizerDriver.getDoubleParamNoNaN(Constants.RESULT_ARIT_MEAN) == 0.0
                    || normalizerDriver.getDoubleParamNoNaN(Constants.RESULT_GEOM_MEAN) == 0.0
                    || normalizerDriver.getDoubleParamNoNaN(Constants.RESULT_HARM_MEAN) == 0.0) {
                normalizerDriver = null;
            } else {
                resultUnit = "% of " + resultUnit;
                if (resultUnitX != null) {
                    resultUnitX = "% of " + resultUnitX;
                }
            }
        }

        // Generate charts 
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        DefaultCategoryDataset datasetX = new DefaultCategoryDataset();

        boolean hasValueX = false;

        int i = 0, thisGroupSize = 0;
        for (; i < nOfTests; i++) {

            for (DriverImpl di : driverInfoList) {
                TestCaseImpl tc = (TestCaseImpl) di.getAggregateTestCases().get(i);

                // User normalizer driver if defined
                if (normalizerDriver != null) {
                    TestCaseImpl normalTc = (TestCaseImpl) normalizerDriver.getAggregateTestCases().get(i);

                    dataset.addValue(
                            normalizerDriver == di ? 100.0
                                    : (100.0 * tc.getDoubleParamNoNaN(Constants.RESULT_VALUE)
                                            / normalTc.getDoubleParamNoNaN(Constants.RESULT_VALUE)),
                            _plotDrivers ? tc.getName() : di.getName(),
                            _plotDrivers ? di.getName() : tc.getName());

                    if (tc.hasParam(Constants.RESULT_VALUE_X)) {
                        datasetX.addValue(
                                (100.0 * tc.getDoubleParamNoNaN(Constants.RESULT_VALUE_X)
                                        / normalTc.getDoubleParamNoNaN(Constants.RESULT_VALUE_X)),
                                _plotDrivers ? tc.getName() : di.getName(),
                                _plotDrivers ? di.getName() : tc.getName());
                        hasValueX = true;
                    }
                } else {
                    dataset.addValue(tc.getDoubleParamNoNaN(Constants.RESULT_VALUE),
                            _plotDrivers ? tc.getName() : di.getName(),
                            _plotDrivers ? di.getName() : tc.getName());

                    if (tc.hasParam(Constants.RESULT_VALUE_X)) {
                        datasetX.addValue(tc.getDoubleParamNoNaN(Constants.RESULT_VALUE_X),
                                _plotDrivers ? tc.getName() : di.getName(),
                                _plotDrivers ? di.getName() : tc.getName());
                        hasValueX = true;
                    }
                }

            }

            thisGroupSize++;

            // Generate chart for this group if complete
            if (thisGroupSize == groupSizes[groupSizesIndex]) {
                int nextPlotIndex = 1;
                CombinedDomainCategoryPlot plot = new CombinedDomainCategoryPlot();

                // Use same renderer in combine charts to get same colors
                BarRenderer3D renderer = new BarRenderer3D();
                renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());

                // Bar chart for secondary data set based on japex.resultValueX
                if (hasValueX) {
                    NumberAxis rangeAxisX = new NumberAxis(resultUnitX);
                    CategoryPlot subplotX = new CategoryPlot(datasetX, null, rangeAxisX, renderer);

                    // Set transparency and clear legend for this plot
                    subplotX.setForegroundAlpha(0.7f);
                    subplotX.setFixedLegendItems(new LegendItemCollection());

                    plot.add(subplotX, nextPlotIndex++);
                    _chartHeight += 50; // Adjust chart height
                }

                // Bar chart for main data set based on japex.resultValue
                NumberAxis rangeAxis = new NumberAxis(resultUnit);
                CategoryPlot subplot = new CategoryPlot(dataset, null, rangeAxis, renderer);
                subplot.setForegroundAlpha(0.7f); // transparency
                plot.add(subplot, nextPlotIndex);

                // Create chart and save it as JPEG
                String chartTitle = _plotDrivers ? "Results per Driver" : "Results per Test";
                JFreeChart chart = new JFreeChart(
                        hasValueX ? chartTitle : (chartTitle + "(" + resultUnit + ")"),
                        new Font("SansSerif", Font.BOLD, 14), plot, true);
                chart.setAntiAlias(true);
                ChartUtilities.saveChartAsJPEG(new File(baseName + Integer.toString(nOfFiles) + extension),
                        chart, _chartWidth, _chartHeight);

                nOfFiles++;
                groupSizesIndex++;
                thisGroupSize = 0;

                // Create fresh data sets
                dataset = new DefaultCategoryDataset();
                datasetX = new DefaultCategoryDataset();
            }
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return nOfFiles;
}

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

public void createGraph(PlotJob job, Map<String, List<Double>> PFTData, Map<String, 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 < job.headers.size(); i++) {
        title = title + job.headers.get(i) + "_";
        XYSeries dataSeries;/* w w w  .  ja v a2 s  .  co  m*/
        dataSeries = plotTool.createXYSeries(job.headers.get(i), data.get("Time(s)"),
                data.get(job.headers.get(i)));
        dataSet.addSeries(dataSeries);
        maxY = maxY < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY;
        minY = minY > dataSeries.getMinY() ? dataSeries.getMinY() : minY;
    }

    //Now make a data series for PFT data and check its max and min
    XYSeries dataSeries = plotTool.createXYSeries("PFT Total Lung Volume (mL)", PFTData.get("Time"),
            PFTData.get("Volume"));
    dataSet.addSeries(dataSeries);
    maxY = maxY < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY;
    minY = minY > dataSeries.getMinY() ? dataSeries.getMinY() : minY;

    title = title + "vs_Time";

    //Override the constructed title if desired
    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));
    }

    //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(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength);
        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);

    formatRPFTPlot(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]);
        }
    }

    //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);

    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:com.sun.japex.ChartGenerator.java

private int generateTestCaseLineCharts(String baseName, String extension) {
    int nOfFiles = 0;
    List<DriverImpl> driverInfoList = _testSuite.getDriverInfoList();

    // Get number of tests from first driver
    final int nOfTests = driverInfoList.get(0).getAggregateTestCases().size();

    int groupSizesIndex = 0;
    int[] groupSizes = calculateGroupSizes(nOfTests, _plotGroupSize);

    try {/*  w  w w  .  j a  v  a2s. c  o m*/
        String resultUnit = _testSuite.getParam(Constants.RESULT_UNIT);

        // Generate charts 
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        int i = 0, thisGroupSize = 0;
        for (; i < nOfTests; i++) {

            for (DriverImpl di : driverInfoList) {
                TestCaseImpl tc = (TestCaseImpl) di.getAggregateTestCases().get(i);

                dataset.addValue(tc.getDoubleParamNoNaN(Constants.RESULT_VALUE),
                        _plotDrivers ? di.getName() : tc.getName(), _plotDrivers ? tc.getName() : di.getName());
            }

            thisGroupSize++;

            // Generate chart for this group if complete
            if (thisGroupSize == groupSizes[groupSizesIndex]) {
                JFreeChart chart = ChartFactory.createLineChart(
                        (_plotDrivers ? "Results per Driver (" : "Results per Test (") + resultUnit + ")", "",
                        resultUnit, dataset, PlotOrientation.VERTICAL, true, true, false);

                configureLineChart(chart);

                chart.setAntiAlias(true);
                ChartUtilities.saveChartAsJPEG(new File(baseName + Integer.toString(nOfFiles) + extension),
                        chart, _chartWidth, _chartHeight);

                nOfFiles++;
                groupSizesIndex++;
                thisGroupSize = 0;
                dataset = new DefaultCategoryDataset();
            }
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return nOfFiles;
}

From source file:com.sun.japex.ChartGenerator.java

private int generateTestCaseScatterCharts(String baseName, String extension) {
    int nOfFiles = 0;
    List<DriverImpl> driverInfoList = _testSuite.getDriverInfoList();

    try {/* ww w .  j  ava  2 s . c  o  m*/
        // Get number of tests from first driver
        final int nOfTests = driverInfoList.get(0).getAggregateTestCases().size();

        DefaultTableXYDataset xyDataset = new DefaultTableXYDataset();

        // Generate charts
        for (DriverImpl di : driverInfoList) {
            XYSeries xySeries = new XYSeries(di.getName(), true, false);
            for (int j = 0; j < nOfTests; j++) {
                TestCaseImpl tc = (TestCaseImpl) di.getAggregateTestCases().get(j);
                try {
                    xySeries.add(tc.getDoubleParamNoNaN(Constants.RESULT_VALUE_X),
                            tc.getDoubleParamNoNaN(Constants.RESULT_VALUE));
                } catch (SeriesException e) {
                    // Ignore duplicate x-valued points
                }

            }
            xyDataset.addSeries(xySeries);
        }

        String resultUnit = _testSuite.getParam(Constants.RESULT_UNIT);
        String resultUnitX = _testSuite.getParam(Constants.RESULT_UNIT_X);

        JFreeChart chart = ChartFactory.createScatterPlot("Results Per Test", resultUnitX, resultUnit,
                xyDataset, PlotOrientation.VERTICAL, true, true, false);

        // Set log scale depending on japex.resultAxis[_X]
        XYPlot plot = chart.getXYPlot();
        if (_testSuite.getParam(Constants.RESULT_AXIS_X).equalsIgnoreCase("logarithmic")) {
            LogarithmicAxis logAxisX = new LogarithmicAxis(resultUnitX);
            logAxisX.setAllowNegativesFlag(true);
            plot.setDomainAxis(logAxisX);
        }
        if (_testSuite.getParam(Constants.RESULT_AXIS).equalsIgnoreCase("logarithmic")) {
            LogarithmicAxis logAxis = new LogarithmicAxis(resultUnit);
            logAxis.setAllowNegativesFlag(true);
            plot.setRangeAxis(logAxis);
        }

        chart.setAntiAlias(true);
        ChartUtilities.saveChartAsJPEG(new File(baseName + Integer.toString(nOfFiles) + extension), chart,
                _chartWidth, _chartHeight);
        nOfFiles++;
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return nOfFiles;
}

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;
        }//ww  w  .  j  a va2s .  c  o m

        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.apache.jmeter.visualizers.CreateReport.java

/**
 * Creates a table; widths are set with setWidths().
 * @return a PdfPTable/*w w w  .java  2s .c o  m*/
 * @throws DocumentException
 */

//createGraphs("Average Response Time of samples for each Request","Average(ms)",2);
public Image createGraphs(String chartName, String colName, int colNo) {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (int i = 0; i < model.getRowCount(); i++)
        dataset.setValue((long) model.getValueAt(i, colNo), "Average", model.getValueAt(i, 0).toString());
    ChartFactory.setChartTheme(StandardChartTheme.createDarknessTheme());

    final JFreeChart chart = ChartFactory.createBarChart3D(chartName, // chart title
            "Requests", // domain axis label

            "Average (ms)", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    final CategoryPlot plot = chart.getCategoryPlot();
    final CategoryAxis axis = plot.getDomainAxis();
    axis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 8.0));
    final BarRenderer3D renderer = (BarRenderer3D) plot.getRenderer();
    renderer.setDrawBarOutline(false);
    renderer.setMaximumBarWidth(0.05);

    try {
        //java.io.OutputStream out= new OutputStream(new FileOutputStream(BASEPATH+"//MyFile.jpg"));
        ChartUtilities.saveChartAsJPEG(new File(BASEPATH + "//MyFile.jpg"), chart, 500, 400);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Image img = null;
    try {
        img = Image.getInstance(BASEPATH + "//MyFile.jpg");
    } catch (BadElementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return img;
}

From source file:AnalysisModule.DataAnalysis.java

public void simulateBitmapAnalyse(List<Scenario> lstScenario) throws Exception {
    Double valor;/*from w  w  w. j  a  v  a 2  s  .  c o m*/

    bitmapAnalyse(lstScenario);
    for (Scenario scenario : lstScenario) {
        for (Topology topology : scenario.lstTopology) {
            File table = new File(topology.getSaidasDir() + "Resumo.csv");
            FileWriter fw = new FileWriter(table);
            PrintWriter pw = new PrintWriter(fw);
            pw.write(";Instancia 1;Instancia 2;Instancia 3;Instancia 4\n");
            pw.write("Tipo;BITMAP;BITMAP;BITMAP;COUNTER\n");
            pw.write("Size(KB);");
            for (Instance instance : topology.getLstInstance()) {
                pw.write(String.format("%6.2f", (instance.getBitMapSize() / 8.0) / 1024.0) + ";");
            }
            pw.write("\n");
            pw.write("Treshold;0,1;0,3;0,5;-\n");
            pw.write("RMSE;");
            for (Instance instance : topology.getLstInstance()) {
                double error = 0;
                int counter = 0;
                for (int i = 0; i < topology.getNumberOfSwitches(); i++) {
                    for (int j = i + 1; j < topology.getNumberOfSwitches(); j++) {
                        error += Math.pow(topology.getTrafficMatrix()[i][j] - instance.trafficMatrix[i][j], 2);
                        counter++;
                    }
                }
                error = Math.sqrt(error / counter);
                System.out.println("RMSE: " + error);
                pw.write(String.format("%10.8f", error) + ";");
            }
            pw.write("\n");
            pw.write("RMSRE;");
            for (Instance instance : topology.getLstInstance()) {
                double error = 0;
                int counter = 0;
                double T = 0;
                for (int i = 0; i < topology.getNumberOfSwitches(); i++) {
                    for (int j = i + 1; j < topology.getNumberOfSwitches(); j++) {
                        if (instance.trafficMatrix[i][j] > T) {
                            error += Math.pow((topology.getTrafficMatrix()[i][j] - instance.trafficMatrix[i][j])
                                    / instance.trafficMatrix[i][j], 2);
                            counter++;
                        }
                    }
                }
                error = Math.sqrt(error / counter);
                System.out.println("RMSRE: " + error);
                pw.write(String.format("%10.8f", error) + ";");
            }
            pw.write("\n");
            pw.write("Observers;");
            for (Instance instance : topology.getLstInstance()) {
                int nbSw = 0;
                for (Switch sw : instance.networkSwitch.values()) {
                    if (sw.isObserver) {
                        nbSw++;
                    }
                }
                pw.write(nbSw + ";");
            }
            pw.write("\n");
            pw.write("RelNbSw;");
            for (Instance instance : topology.getLstInstance()) {
                int nbSw = 0;
                for (Switch sw : instance.networkSwitch.values()) {
                    if (sw.isObserver) {
                        nbSw++;
                    }
                }
                pw.write(String.format("%4.2f", 100.0 * (float) nbSw / (float) topology.getNumberOfSwitches())
                        + ";");
            }
            pw.write("\n");
            pw.close();
            fw.close();
            for (Instance instance : topology.getLstInstance()) {
                HashMap<Double, List<HashMap<Integer, Integer>>> orderMap = new HashMap<>();
                File bmpFile = new File(
                        topology.getSaidasDir() + "SimulacaoInstancia" + instance.getId() + ".csv");
                if (!bmpFile.exists()) {
                    bmpFile.createNewFile();
                }
                FileWriter fout = new FileWriter(bmpFile);
                PrintWriter oos = new PrintWriter(fout);
                for (int i = 0; i < topology.getNumberOfSwitches(); i++) {
                    oos.print(";Router " + (i + 1));
                }
                for (int i = 0; i < topology.getNumberOfSwitches(); i++) {
                    oos.println();
                    oos.print("Router " + (i + 1));
                    for (int j = 0; j < topology.getNumberOfSwitches(); j++) {
                        int sourceId = i;
                        int destinationId = j;
                        if (sourceId > topology.getNumberOfSwitches()
                                || destinationId > topology.getNumberOfSwitches()) {
                            System.out.println("Erro no nmero de switches");
                            throw new Exception("Erro no nmero de switches");
                        } else {
                            doPrintElement(oos, i, j, instance.trafficMatrix[i][j]);

                            //                                if (i < j) {
                            //                                    if (orderMap.containsKey(instance.trafficMatrix[i][j])) {
                            //
                            //                                        HashMap<Integer, Integer> mapNodes = new HashMap<>();
                            //                                        mapNodes.put(i + 1, j + 1);
                            //                                        orderMap.get(instance.trafficMatrix[i][j]).add(mapNodes);
                            //                                    } else {
                            //                                        LinkedList listaHashMap = new LinkedList();
                            //                                        HashMap<Integer, Integer> mapNodes = new HashMap<>();
                            //                                        mapNodes.put(i + 1, j + 1);
                            //                                        listaHashMap.add(mapNodes);
                            //                                        orderMap.put(instance.trafficMatrix[i][j], listaHashMap);
                            //                                    }
                            //                                }
                        }
                    }
                }
                oos.close();
                fout.close();

                //                    Map<Double, List<HashMap<Integer, Integer>>> map = new TreeMap<>(orderMap);
                //                    System.out.println("Instancia" + instance.getId() + " After Sorting:");
                //                    Set set2 = map.entrySet();
                //                    Iterator iterator2 = set2.iterator();
                //                    while (iterator2.hasNext()) {
                //                        Map.Entry me2 = (Map.Entry) iterator2.next();
                //                        System.out.print(me2.getKey() + ": ");
                //                        System.out.println(me2.getValue());
                //                    }
                // Plot Graf
                XYSeries matrix = new XYSeries("Matrix", false, true);
                for (int i = 0; i < topology.getNumberOfSwitches(); i++) {
                    for (int j = i + 1; j < topology.getNumberOfSwitches(); j++) {
                        matrix.add((double) topology.getTrafficMatrix()[i][j], instance.trafficMatrix[i][j]);
                    }
                }
                double maxPlot = Double.max(matrix.getMaxX(), matrix.getMaxY()) * 1.1;
                XYSeries middle = new XYSeries("Real");
                middle.add(0, 0);
                middle.add(maxPlot, maxPlot);
                XYSeries max = new XYSeries("Max");
                max.add(0, 0);
                max.add(maxPlot, maxPlot * 1.2);
                XYSeries min = new XYSeries("Min");
                min.add(0, 0);
                min.add(maxPlot, maxPlot * 0.8);

                XYSeriesCollection dataset = new XYSeriesCollection();
                dataset.addSeries(middle);
                dataset.addSeries(matrix);
                dataset.addSeries(max);
                dataset.addSeries(min);
                JFreeChart chart = ChartFactory.createXYLineChart("Matriz de Trfego", "Real", "Estimado",
                        dataset);
                chart.setBackgroundPaint(new ChartColor(255, 255, 255));

                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
                renderer.setSeriesLinesVisible(1, false);
                renderer.setSeriesShapesVisible(1, true);

                int width = 640 * 2; /* Width of the image */

                int height = 480 * 2; /* Height of the image */

                File XYChart = new File(
                        topology.getSaidasDir() + "SimulacaoInstancia" + instance.getId() + ".jpeg");
                ChartUtilities.saveChartAsJPEG(XYChart, chart, width, height);
            }
        }
    }
}

From source file:org.moeaframework.analysis.plot.Plot.java

/**
 * Saves the plot to an image file.  The format must be one of {@code png},
 * {@code jpeg}, or {@code svg} (requires JFreeSVG).
 * // w w  w.jav  a  2s .  c o  m
 * @param file the file
 * @param format the image format
 * @param width the image width
 * @param height the image height
 * @return a reference to this {@code Plot} instance
 * @throws IOException if an I/O error occurred
 */
public Plot save(File file, String format, int width, int height) throws IOException {
    if (format.equalsIgnoreCase("PNG")) {
        ChartUtilities.saveChartAsPNG(file, chart, width, height);
    } else if (format.equalsIgnoreCase("JPG") || format.equalsIgnoreCase("JPEG")) {
        ChartUtilities.saveChartAsJPEG(file, chart, width, height);
    } else if (format.equalsIgnoreCase("SVG")) {
        String svg = generateSVG(width, height);
        BufferedWriter writer = null;

        try {
            writer = new BufferedWriter(new FileWriter(file));
            writer.write(
                    "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
            writer.write(svg);
            writer.write("\n");
            writer.flush();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    return this;
}