Example usage for org.jfree.chart.renderer.xy XYLineAndShapeRenderer XYLineAndShapeRenderer

List of usage examples for org.jfree.chart.renderer.xy XYLineAndShapeRenderer XYLineAndShapeRenderer

Introduction

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

Prototype

public XYLineAndShapeRenderer(boolean lines, boolean shapes) 

Source Link

Document

Creates a new renderer.

Usage

From source file:net.sf.mzmine.modules.visualization.tic.TICPlot.java

public synchronized void addLabelledPeakDataset(final XYDataset dataSet, final String label) {

    // Add standard peak data set.
    addPeakDataset(dataSet);/*from  www  .  jav  a  2 s. c  o  m*/

    // Do we have a label?
    if (label != null && label.length() > 0) {

        // Add peak label renderer and data set.
        final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(false, false);
        renderer.setBaseItemLabelsVisible(labelsVisible == 2);
        renderer.setBaseItemLabelPaint(LABEL_COLOR);
        addDataSetRenderer(dataSet, renderer);
        renderer.setBaseItemLabelGenerator(new XYItemLabelGenerator() {

            @Override
            public String generateLabel(final XYDataset xyDataSet, final int series, final int item) {

                return ((PeakDataSet) xyDataSet).isPeak(item) ? label : null;
            }
        });

        numOfPeaks++;
        havePeakLabels = true;
    }
}

From source file:org.gwaspi.reports.GenericReportGenerator.java

public static XYPlot buildQQPlot(OperationKey testOpKey, int df) throws IOException {

    if (df != 1 && df != 2) {
        throw new IllegalArgumentException("Only df = 1 or 2 is supported; it is " + df);
    }/*from   ww  w  .jav a  2  s. c  o m*/

    //<editor-fold defaultstate="expanded" desc="PLOT DEFAULTS">
    final Config config = Config.getSingleton();
    final Color background = config.getColor(PLOT_QQ_BACKGROUND_CONFIG, PLOT_QQ_BACKGROUND_DEFAULT);
    final Color actual = config.getColor(PLOT_QQ_ACTUAL_CONFIG, PLOT_QQ_ACTUAL_DEFAULT);
    final Color sigma = config.getColor(PLOT_QQ_SIGMA_CONFIG, PLOT_QQ_SIGMA_DEFAULT);
    final Color mu = config.getColor(PLOT_QQ_MU_CONFIG, PLOT_QQ_MU_DEFAULT);
    //</editor-fold>

    //<editor-fold defaultstate="expanded" desc="GET X^2">
    List<Double> obsChiSqrVals = assembleQQPlotData(testOpKey);

    int N = obsChiSqrVals.size();
    List<Double> expChiSqrDist;
    if (df == 1) {
        expChiSqrDist = Chisquare.getChiSquareDistributionDf1(N, 1.0f);
    } else { // df == 2
        expChiSqrDist = Chisquare.getChiSquareDistributionDf2(N, 1.0f);
    }
    Collections.sort(expChiSqrDist);
    //</editor-fold>

    //<editor-fold defaultstate="expanded" desc="GET CONFIDENCE BOUNDARY">
    InputStream boundaryStream = GenericReportGenerator.class
            .getResourceAsStream("/samples/chisqrboundary-df" + df + ".txt");
    InputStreamReader isr = new InputStreamReader(boundaryStream);
    BufferedReader inputBufferReader = new BufferedReader(isr);

    Double stopValue = expChiSqrDist.get(N - 1);
    Double currentValue = 0d;
    List<Double[]> boundary = new ArrayList<Double[]>();
    while (currentValue <= stopValue) {
        String l = inputBufferReader.readLine();
        if (l == null) {
            break;
        }
        String[] cVals = l.split(",");
        Double[] slice = new Double[3];
        slice[0] = Double.parseDouble(cVals[0]);
        slice[1] = Double.parseDouble(cVals[1]);
        slice[2] = Double.parseDouble(cVals[2]);
        currentValue = slice[1];
        boundary.add(slice);
    }
    inputBufferReader.close();
    //</editor-fold>

    XYSeriesCollection dataSeries = new XYSeriesCollection();
    XYSeries seriesData = new XYSeries("X");
    XYSeries seriesRef = new XYSeries("Expected");

    for (int i = 0; i < obsChiSqrVals.size(); i++) {
        double obsVal = obsChiSqrVals.get(i);
        double expVal = expChiSqrDist.get(i);

        seriesData.add(expVal, obsVal);
        seriesRef.add(expVal, expVal);
    }

    //constant chi-square boundaries
    XYSeries seriesLower = new XYSeries("2 boundary");
    XYSeries seriesUpper = new XYSeries("");
    for (Double[] slice : boundary) {
        seriesUpper.add(slice[1], slice[0]);
        seriesLower.add(slice[1], slice[2]);
    }

    dataSeries.addSeries(seriesData);
    dataSeries.addSeries(seriesRef);
    dataSeries.addSeries(seriesUpper);
    dataSeries.addSeries(seriesLower);
    final XYDataset data = dataSeries;

    //create QQ plot
    final boolean withLegend = true;
    JFreeChart chart = ChartFactory.createScatterPlot("QQ-plot", "Exp X", "Obs X", data,
            PlotOrientation.VERTICAL, withLegend, false, false);

    final XYPlot plot = chart.getXYPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(false, true);
    renderer.setSeriesPaint(0, actual);
    renderer.setSeriesPaint(1, mu);
    renderer.setSeriesPaint(2, sigma);
    renderer.setSeriesPaint(3, sigma);

    renderer.setBaseShapesVisible(true);
    renderer.setBaseShapesFilled(true);
    renderer.setSeriesShape(0, new Rectangle2D.Double(-1.0, -1.0, 2.0, 2.0));
    renderer.setSeriesShape(1, new Rectangle2D.Double(-1.0, -1.0, 2.0, 2.0));
    renderer.setSeriesShape(2, new Rectangle2D.Double(-1.0, -1.0, 2.0, 2.0));
    renderer.setSeriesShape(3, new Rectangle2D.Double(-1.0, -1.0, 2.0, 2.0));

    plot.setRenderer(renderer);

    // PLOT BACKGROUND COLOR
    plot.setBackgroundPaint(background); // Hue, saturation, brightness

    return plot;
}

From source file:org.deegree.graphics.charts.ChartsBuilder.java

/**
 * Configures the pie chart according to the stored configurations file
 *
 * @param chart//from w  w  w.j a va2 s. com
 * @param chartConfigs
 *            to configure the output chart
 * @return configured JFreeChart
 */
protected JFreeChart configLineChart(JFreeChart chart, ChartConfig chartConfigs) {

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(chartConfigs.isLineRenderLines(),
            chartConfigs.isLineRenderShapes());

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setRenderer(renderer);
    return chart;
}

From source file:org.gumtree.vis.awt.PlotFactory.java

/**
 * Creates and returns a time series chart.  A time series chart is an
 * {@link XYPlot} with a {@link DateAxis} for the x-axis and a
 * {@link NumberAxis} for the y-axis.  The default renderer is an
 * {@link XYLineAndShapeRenderer}.//  w w w. j  a va  2s  .  c  om
 * <P>
 * A convenient dataset to use with this chart is a
 * {@link org.jfree.data.time.TimeSeriesCollection}.
 *
 * @param title  the chart title (<code>null</code> permitted).
 * @param timeAxisLabel  a label for the time axis (<code>null</code>
 *                       permitted).
 * @param valueAxisLabel  a label for the value axis (<code>null</code>
 *                        permitted).
 * @param dataset  the dataset for the chart (<code>null</code> permitted).
 * @param legend  a flag specifying whether or not a legend is required.
 * @param tooltips  configure chart to generate tool tips?
 * @param urls  configure chart to generate URLs?
 *
 * @return A time series chart.
 */
public static JFreeChart createTimeSeriesChart(String title, String timeAxisLabel, String valueAxisLabel,
        XYDataset dataset, boolean legend, boolean tooltips, boolean urls) {

    ValueAxis timeAxis = new DateAxis(timeAxisLabel);
    timeAxis.setLowerMargin(0.02); // reduce the default margins
    timeAxis.setUpperMargin(0.02);
    //        NumberAxis valueAxis = new NumberAxis(valueAxisLabel);
    LogAxis valueAxis = new LogAxis(valueAxisLabel);
    //        valueAxis.setAutoRangeIncludesZero(false);  // override default
    XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, null);

    XYToolTipGenerator toolTipGenerator = null;
    if (tooltips) {
        toolTipGenerator = StandardXYToolTipGenerator.getTimeSeriesInstance();
    }

    XYURLGenerator urlGenerator = null;
    if (urls) {
        urlGenerator = new StandardXYURLGenerator();
    }

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
    renderer.setBaseToolTipGenerator(toolTipGenerator);
    renderer.setURLGenerator(urlGenerator);
    plot.setRenderer(renderer);

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);
    ChartFactory.getChartTheme().apply(chart);
    return chart;

}

From source file:de.bund.bfr.knime.pmmlite.views.chart.ChartCreator.java

private XYItemRenderer createRenderer(String id, Color defaultColor, NamedShape defaultShape,
        XYDataset dataSet) {//www .j  a  v  a 2s .  c  om
    Color color = colors.containsKey(id) ? colors.get(id) : defaultColor;
    NamedShape shape = shapes.containsKey(id) ? shapes.get(id) : defaultShape;

    if (dataSet instanceof YIntervalSeriesCollection) {
        DeviationRenderer renderer = new DeviationRenderer(drawLines, !drawLines);

        renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
        renderer.setSeriesPaint(0, color);
        renderer.setSeriesFillPaint(0, color);
        renderer.setSeriesShape(0, shape.getShape());

        return renderer;
    } else {
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(drawLines, !drawLines);

        renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
        renderer.setSeriesPaint(0, color);
        renderer.setSeriesShape(0, shape.getShape());

        return renderer;
    }
}

From source file:umontreal.iro.lecuyer.charts.XYLineChart.java

/**
 * Displays bar chart on the screen using Swing.
 *    This method creates an application containing a bar chart panel displaying
 *    the chart.  The created frame is positioned on-screen, and displayed before
 *    it is returned. The <TT>width</TT> and the <TT>height</TT>
 *    of the chart are measured in pixels.
 * /*from  w  w w .j a  va 2 s  .  c o  m*/
 * @param width frame width in pixels.
 * 
 *    @param height frame height in pixels.
 * 
 *    @return frame containing the bar chart.;
 * 
 */
public JFrame viewBar(int width, int height) {
    JFrame myFrame;
    if (chart.getTitle() != null)
        myFrame = new JFrame("XYLineChart from SSJ: " + chart.getTitle().getText());
    else
        myFrame = new JFrame("XYLineChart from SSJ");

    XYPlot plot = (XYPlot) chart.getPlot();

    //Create the bar
    plot.setDataset(0, dataset.getSeriesCollection());
    final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(false, true);
    renderer.setSeriesPaint(0, Color.ORANGE);
    renderer.setSeriesShape(0, new Line2D.Double(0, 0, 0, 1000));
    plot.setRenderer(0, renderer);

    //Create the points
    plot.setDataset(1, dataset.getSeriesCollection());
    final XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(false, true);
    renderer2.setSeriesPaint(0, Color.ORANGE);
    renderer2.setSeriesShape(0, new Ellipse2D.Double(-2.0, -2.0, 4.0, 4.0));
    plot.setRenderer(1, renderer2);

    ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(width, height));
    myFrame.setContentPane(chartPanel);
    myFrame.pack();
    myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    myFrame.setLocationRelativeTo(null);
    myFrame.setVisible(true);
    return myFrame;
}

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 . c  om

        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.moeaframework.analysis.plot.Plot.java

/**
 * Creates a new line plot series.  The series is added to the given
 * dataset, or if {@code null} a new dataset is created.
 * /*from ww w. j a v  a  2s  . c om*/
 * @param label the label for the series
 * @param x the x values
 * @param y the y values
 * @param dataset the dataset, or {@code null} if a new dataset should be
 *        created
 * @return a reference to this {@code Plot} instance
 */
private Plot line(String label, List<? extends Number> x, List<? extends Number> y,
        XYSeriesCollection dataset) {
    if (dataset == null) {
        createXYPlot();
        currentDataset++;
        dataset = new XYSeriesCollection();
    }

    // generate the dataset
    XYSeries series = new XYSeries(label, false, true);

    for (int i = 0; i < x.size(); i++) {
        series.add(x.get(i), y.get(i));
    }

    dataset.addSeries(series);

    // add the dataset to the plot
    XYPlot plot = chart.getXYPlot();
    plot.setDataset(currentDataset, dataset);

    // setup the renderer
    Paint paint = paintHelper.get(dataset.getSeriesKey(0));
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
    renderer.setAutoPopulateSeriesStroke(false);

    renderer.setBaseStroke(new BasicStroke(3f, 1, 1));
    renderer.setBasePaint(paint);
    renderer.setBaseFillPaint(paint);

    plot.setRenderer(currentDataset, renderer);

    return this;
}

From source file:de.bund.bfr.knime.pmm.common.chart.ChartCreator.java

private void plotDataSet(XYPlot plot, Plotable plotable, String id, Color defaultColor, Shape defaultShape)
        throws ConvertException {
    double[][] points = plotable.getPoints(paramX, paramY, unitX, unitY, transformX, transformY);
    String legend = shortLegend.get(id);
    Color color = colors.get(id);
    Shape shape = shapes.get(id);

    if (addInfoInLegend) {
        legend = longLegend.get(id);/*from w w  w  .j  a v  a 2  s .co  m*/
    }

    if (color == null) {
        color = defaultColor;
    }

    if (shape == null) {
        shape = defaultShape;
    }

    if (points != null) {
        DefaultXYDataset dataset = new DefaultXYDataset();
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(drawLines, true);

        dataset.addSeries(legend, points);
        renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
        renderer.setSeriesPaint(0, color);
        renderer.setSeriesShape(0, shape);

        int i;

        if (plot.getDataset(0) == null) {
            i = 0;
        } else {
            i = plot.getDatasetCount();
        }

        plot.setDataset(i, dataset);
        plot.setRenderer(i, renderer);
    }
}

From source file:org.yardstickframework.report.jfreechart.JFreeChartGraphPlotter.java

/**
 * @param folderToWrite Folder to write the resulted charts.
 * @param plots Collections of plots./*ww w .  j a  va2 s.c om*/
 * @param infoMap Map with additional plot info.
 * @param mode Generation mode.
 * @throws Exception If failed.
 */
private static void processPlots(File folderToWrite, Collection<List<PlotData>> plots,
        Map<String, List<JFreeChartPlotInfo>> infoMap, JFreeChartGenerationMode mode) throws Exception {
    ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);

    int idx = -1;

    while (true) {
        idx++;

        DefaultXYDataset dataSet = new DefaultXYDataset();

        List<JFreeChartPlotInfo> infoList = new ArrayList<>();

        String xAxisLabel = "";
        String yAxisLabel = "";
        String plotName = "";

        int cnt = 0;

        for (List<PlotData> plotData0 : plots) {
            if (plotData0.size() <= idx)
                continue;

            PlotData plotData = plotData0.get(idx);

            dataSet.addSeries(plotData.plotName() + "_" + cnt++, plotData.series().data);

            xAxisLabel = plotData.xAxisLabel;
            yAxisLabel = plotData.yAxisLabel;
            plotName = plotData.plotName();

            infoList.add(info(plotData.series(), mode));
        }

        if (infoList.isEmpty())
            break;

        JFreeChart chart = ChartFactory.createXYLineChart("", xAxisLabel, yAxisLabel, dataSet,
                PlotOrientation.VERTICAL, false, false, false);

        AxisSpace as = new AxisSpace();

        as.add(150, RectangleEdge.LEFT);

        XYPlot plot = (XYPlot) chart.getPlot();

        BasicStroke stroke = new BasicStroke(1);

        plot.setRenderer(renderer);
        plot.setBackgroundPaint(WHITE);
        plot.setRangeGridlinePaint(GRAY);
        plot.setDomainGridlinePaint(GRAY);
        plot.setFixedRangeAxisSpace(as);
        plot.setOutlineStroke(stroke);

        for (int i = 0; i < infoList.size(); i++) {
            Color color = PLOT_COLORS[i % PLOT_COLORS.length];

            renderer.setSeriesPaint(i, color);
            renderer.setSeriesStroke(i, new BasicStroke(3)); // Line thickness.

            infoList.get(i).color(Integer.toHexString(color.getRGB()).substring(2));
        }

        ValueAxis axis = plot.getRangeAxis();

        Font font = new Font("Helvetica,Arial,sans-serif", Font.BOLD, axis.getTickLabelFont().getSize() + 5);

        axis.setTickLabelFont(font);
        axis.setLabelFont(font);
        plot.getDomainAxis().setTickLabelFont(font);
        plot.getDomainAxis().setLabelFont(font);

        chart.setTitle(new TextTitle(yAxisLabel, new Font(font.getName(), font.getStyle(), 30)));

        File res = new File(folderToWrite, plotName + ".png");

        ChartUtilities.saveChartAsPNG(res, chart, 1000, 500, info);

        infoMap.put(res.getAbsolutePath(), infoList);

        println("Chart is saved to file: ", res);
    }
}