Example usage for org.jfree.chart LegendItemCollection getItemCount

List of usage examples for org.jfree.chart LegendItemCollection getItemCount

Introduction

In this page you can find the example usage for org.jfree.chart LegendItemCollection getItemCount.

Prototype

public int getItemCount() 

Source Link

Document

Returns the number of legend items in the collection.

Usage

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;//from  w ww  .  ja va2 s .c  om
        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: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 ww. j av a 2s . co  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:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.CombinedCategoryBar.java

public JFreeChart createChart(DatasetMap datasets) {
    logger.debug("IN");

    // recover the datasets
    DefaultCategoryDataset datasetBarFirstAxis = (DefaultCategoryDataset) datasets.getDatasets().get("1-bar");
    DefaultCategoryDataset datasetBarSecondAxis = (DefaultCategoryDataset) datasets.getDatasets().get("2-bar");
    DefaultCategoryDataset datasetLineFirstAxis = (DefaultCategoryDataset) datasets.getDatasets().get("1-line");
    DefaultCategoryDataset datasetLineSecondAxis = (DefaultCategoryDataset) datasets.getDatasets()
            .get("2-line");

    // create the two subplots
    CategoryPlot subPlot1 = new CategoryPlot();
    CategoryPlot subPlot2 = new CategoryPlot();
    CombinedDomainCategoryPlot plot = new CombinedDomainCategoryPlot();

    subPlot1.setDataset(0, datasetBarFirstAxis);
    subPlot2.setDataset(0, datasetBarSecondAxis);

    subPlot1.setDataset(1, datasetLineFirstAxis);
    subPlot2.setDataset(1, datasetLineSecondAxis);

    // localize numbers on y axis
    NumberFormat nf = (NumberFormat) NumberFormat.getNumberInstance(locale);

    // Range Axis 1
    NumberAxis rangeAxis = new NumberAxis(getValueLabel());
    rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setLabelPaint(styleXaxesLabels.getColor());
    rangeAxis// w w  w.ja v  a 2s .  c o  m
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor());
    rangeAxis.setUpperMargin(0.10);
    rangeAxis.setNumberFormatOverride(nf);
    subPlot1.setRangeAxis(rangeAxis);
    if (rangeIntegerValues == true) {
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }

    // Range Axis 2
    NumberAxis rangeAxis2 = new NumberAxis(secondAxisLabel);
    rangeAxis2.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis2.setLabelPaint(styleXaxesLabels.getColor());
    rangeAxis2
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis2.setTickLabelPaint(styleXaxesLabels.getColor());
    rangeAxis2.setUpperMargin(0.10);
    rangeAxis2.setNumberFormatOverride(nf);
    subPlot2.setRangeAxis(rangeAxis2);
    if (rangeIntegerValues == true) {
        rangeAxis2.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }

    // Category Axis
    CategoryAxis domainAxis = new CategoryAxis(getCategoryLabel());
    domainAxis.setLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setLabelPaint(styleYaxesLabels.getColor());
    domainAxis
            .setTickLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setTickLabelPaint(styleYaxesLabels.getColor());
    domainAxis.setUpperMargin(0.10);
    plot.setDomainAxis(domainAxis);
    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setRangeGridlinesVisible(true);
    plot.setDomainGridlinesVisible(true);

    // Add subplots to main plot
    plot.add(subPlot1, 1);
    plot.add(subPlot2, 2);

    MyStandardCategoryItemLabelGenerator generator = null;

    // value labels and additional values are mutually exclusive
    if (showValueLabels == true)
        additionalLabels = false;

    if (additionalLabels) {
        generator = new MyStandardCategoryItemLabelGenerator(catSerLabels, "{1}", NumberFormat.getInstance());
    }

    //      Create Renderers!
    CategoryItemRenderer barRenderer1 = new BarRenderer();
    CategoryItemRenderer barRenderer2 = new BarRenderer();
    LineAndShapeRenderer lineRenderer1 = (useLinesRenderers == true) ? new LineAndShapeRenderer() : null;
    LineAndShapeRenderer lineRenderer2 = (useLinesRenderers == true) ? new LineAndShapeRenderer() : null;

    subPlot1.setRenderer(0, barRenderer1);
    subPlot2.setRenderer(0, barRenderer2);

    if (useLinesRenderers == true) {
        subPlot1.setRenderer(1, lineRenderer1);
        subPlot2.setRenderer(1, lineRenderer2);

        // no shapes for line_no_shapes  series
        for (Iterator iterator = lineNoShapeSeries1.iterator(); iterator.hasNext();) {
            String ser = (String) iterator.next();
            // if there iS a abel associated search for that
            String label = null;
            if (seriesLabelsMap != null) {
                label = (String) seriesLabelsMap.get(ser);
            }
            if (label == null)
                label = ser;
            int index = datasetLineFirstAxis.getRowIndex(label);
            if (index != -1) {
                lineRenderer1.setSeriesShapesVisible(index, false);
            }
        }
        for (Iterator iterator = lineNoShapeSeries2.iterator(); iterator.hasNext();) {
            String ser = (String) iterator.next();
            // if there iS a abel associated search for that

            String label = null;
            if (seriesLabelsMap != null) {
                label = (String) seriesLabelsMap.get(ser);
            }
            if (label == null)
                label = ser;
            int index = datasetLineSecondAxis.getRowIndex(label);
            if (index != -1) {
                lineRenderer2.setSeriesShapesVisible(index, false);
            }
        }

    }

    // add tooltip if enabled
    if (enableToolTips) {
        MyCategoryToolTipGenerator generatorToolTip = new MyCategoryToolTipGenerator(freeToolTips,
                seriesTooltip, categoriesTooltip, seriesCaptions);
        barRenderer1.setToolTipGenerator(generatorToolTip);
        barRenderer2.setToolTipGenerator(generatorToolTip);
        if (useLinesRenderers) {
            lineRenderer1.setToolTipGenerator(generatorToolTip);
            lineRenderer2.setToolTipGenerator(generatorToolTip);
        }
    }

    subPlot1.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    subPlot2.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

    // COnfigure renderers: I do in extensive way so will be easier to add customization in the future

    if (maxBarWidth != null) {
        ((BarRenderer) barRenderer1).setMaximumBarWidth(maxBarWidth.doubleValue());
        ((BarRenderer) barRenderer2).setMaximumBarWidth(maxBarWidth.doubleValue());
    }

    // Values or addition Labels for first BAR Renderer
    if (showValueLabels) {
        barRenderer1.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
        barRenderer1.setBaseItemLabelsVisible(true);
        barRenderer1.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        barRenderer1.setBaseItemLabelPaint(styleValueLabels.getColor());

        barRenderer1.setBasePositiveItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));

        barRenderer1.setBaseNegativeItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));

        barRenderer2.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
        barRenderer2.setBaseItemLabelsVisible(true);
        barRenderer2.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        barRenderer2.setBaseItemLabelPaint(styleValueLabels.getColor());

        barRenderer2.setBasePositiveItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));

        barRenderer2.setBaseNegativeItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));

    } else if (additionalLabels) {
        barRenderer1.setBaseItemLabelGenerator(generator);
        barRenderer2.setBaseItemLabelGenerator(generator);

        double orient = (-Math.PI / 2.0);
        if (styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) {
            orient = 0.0;
        }

        barRenderer1.setBasePositiveItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient));
        barRenderer1.setBaseNegativeItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient));
        barRenderer2.setBasePositiveItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient));
        barRenderer2.setBaseNegativeItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient));

    }

    // Values or addition Labels for line Renderers if requested
    if (useLinesRenderers == true) {
        if (showValueLabels) {
            lineRenderer1.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
            lineRenderer1.setBaseItemLabelsVisible(true);
            lineRenderer1.setBaseItemLabelFont(
                    new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
            lineRenderer1.setBaseItemLabelPaint(styleValueLabels.getColor());
            lineRenderer1.setBasePositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
            lineRenderer1.setBaseNegativeItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
            lineRenderer2.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
            lineRenderer2.setBaseItemLabelsVisible(true);
            lineRenderer2.setBaseItemLabelFont(
                    new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
            lineRenderer2.setBaseItemLabelPaint(styleValueLabels.getColor());
            lineRenderer2.setBasePositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
            lineRenderer2.setBaseNegativeItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));

        } else if (additionalLabels) {
            lineRenderer1.setBaseItemLabelGenerator(generator);
            lineRenderer2.setBaseItemLabelGenerator(generator);
            double orient = (-Math.PI / 2.0);
            if (styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) {
                orient = 0.0;
            }
            lineRenderer1.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));
            lineRenderer1.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));
            lineRenderer2.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));
            lineRenderer2.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));

        }
    }

    // Bar Dataset Colors!
    if (colorMap != null) {
        int idx = -1;
        for (Iterator iterator = datasetBarFirstAxis.getRowKeys().iterator(); iterator.hasNext();) {
            idx++;
            String serName = (String) iterator.next();
            String labelName = "";
            int index = -1;

            if (seriesCaptions != null && seriesCaptions.size() > 0) {
                labelName = serName;
                serName = (String) seriesCaptions.get(serName);
                index = datasetBarFirstAxis.getRowIndex(labelName);
            } else
                index = datasetBarFirstAxis.getRowIndex(serName);

            Color color = (Color) colorMap.get(serName);
            if (color != null) {
                barRenderer1.setSeriesPaint(index, color);
            }
        }

        for (Iterator iterator = datasetBarSecondAxis.getRowKeys().iterator(); iterator.hasNext();) {
            idx++;
            String serName = (String) iterator.next();
            String labelName = "";
            int index = -1;

            if (seriesCaptions != null && seriesCaptions.size() > 0) {
                labelName = serName;
                serName = (String) seriesCaptions.get(serName);
                index = datasetBarSecondAxis.getRowIndex(labelName);
            } else
                index = datasetBarSecondAxis.getRowIndex(serName);

            Color color = (Color) colorMap.get(serName);
            if (color != null) {
                barRenderer2.setSeriesPaint(index, color);
            }
        }
    }

    // LINE Dataset Colors!
    if (useLinesRenderers == true) {
        if (colorMap != null) {
            int idx = -1;
            for (Iterator iterator = datasetLineFirstAxis.getRowKeys().iterator(); iterator.hasNext();) {
                idx++;
                String serName = (String) iterator.next();
                String labelName = "";
                int index = -1;

                if (seriesCaptions != null && seriesCaptions.size() > 0) {
                    labelName = serName;
                    serName = (String) seriesCaptions.get(serName);
                    index = datasetLineFirstAxis.getRowIndex(labelName);
                } else
                    index = datasetLineFirstAxis.getRowIndex(serName);

                Color color = (Color) colorMap.get(serName);
                if (color != null) {
                    lineRenderer1.setSeriesPaint(index, color);
                }
            }

            for (Iterator iterator = datasetLineSecondAxis.getRowKeys().iterator(); iterator.hasNext();) {
                idx++;
                String serName = (String) iterator.next();
                String labelName = "";
                int index = -1;

                if (seriesCaptions != null && seriesCaptions.size() > 0) {
                    labelName = serName;
                    serName = (String) seriesCaptions.get(serName);
                    index = datasetLineSecondAxis.getRowIndex(labelName);
                } else
                    index = datasetLineSecondAxis.getRowIndex(serName);

                Color color = (Color) colorMap.get(serName);
                if (color != null) {
                    lineRenderer2.setSeriesPaint(index, color);
                }
            }
        }
    }

    //defines url for drill
    boolean document_composition = false;
    if (mode.equalsIgnoreCase(SpagoBIConstants.DOCUMENT_COMPOSITION))
        document_composition = true;

    logger.debug("Calling Url Generation");

    MyCategoryUrlGenerator mycatUrl = null;
    if (super.rootUrl != null) {
        logger.debug("Set MycatUrl");
        mycatUrl = new MyCategoryUrlGenerator(super.rootUrl);

        mycatUrl.setDocument_composition(document_composition);
        mycatUrl.setCategoryUrlLabel(super.categoryUrlName);
        mycatUrl.setSerieUrlLabel(super.serieUrlname);
        mycatUrl.setDrillDocTitle(drillDocTitle);
        mycatUrl.setTarget(target);
    }
    if (mycatUrl != null) {
        barRenderer1.setItemURLGenerator(mycatUrl);
        barRenderer2.setItemURLGenerator(mycatUrl);
        if (useLinesRenderers) {
            lineRenderer1.setItemURLGenerator(mycatUrl);
            lineRenderer2.setItemURLGenerator(mycatUrl);
        }

    }

    plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);

    JFreeChart chart = new JFreeChart(plot);
    TextTitle title = setStyleTitle(name, styleTitle);
    chart.setTitle(title);
    if (subName != null && !subName.equals("")) {
        TextTitle subTitle = setStyleTitle(subName, styleSubTitle);
        chart.addSubtitle(subTitle);
    }
    chart.setBackgroundPaint(Color.white);

    //      I want to re order the legend
    LegendItemCollection legends = plot.getLegendItems();
    // legend Temp 
    HashMap<String, LegendItem> legendTemp = new HashMap<String, LegendItem>();
    Vector<String> alreadyInserted = new Vector<String>();
    for (int i = 0; i < legends.getItemCount(); i++) {
        LegendItem item = legends.get(i);
        String label = item.getLabel();
        legendTemp.put(label, item);
    }
    LegendItemCollection newLegend = new LegendItemCollection();
    // force the order of the ones specified
    for (Iterator iterator = seriesOrder.iterator(); iterator.hasNext();) {
        String serie = (String) iterator.next();
        if (legendTemp.keySet().contains(serie)) {
            newLegend.add(legendTemp.get(serie));
            alreadyInserted.add(serie);
        }
    }
    // check that there are no serie not specified, otherwise add them
    for (Iterator iterator = legendTemp.keySet().iterator(); iterator.hasNext();) {
        String serie = (String) iterator.next();
        if (!alreadyInserted.contains(serie)) {
            newLegend.add(legendTemp.get(serie));
        }
    }

    plot.setFixedLegendItems(newLegend);

    if (legend == true)
        drawLegend(chart);
    logger.debug("OUT");

    return chart;

}

From source file:edu.jhuapl.graphs.controller.GraphController.java

/**
 * The useItemColor is still under development to allow each bar to be a different color.
 *//*from  ww w .j av  a2s  .  c o  m*/
private double setDataSeries(GraphDataInterface graphData, String displayKey, boolean useNoDataColor,
        List<DataSeries> dataSeries, LegendItemCollection legendItems, boolean useItemColor) {
    double[][] counts = graphData.getCounts();
    int[][] colors = graphData.getColors();
    String[][] altTexts = graphData.getAltTexts();
    String[][] lineSetURLs = graphData.getLineSetURLs();
    String[] xLabels = graphData.getXLabels();
    String[] lineSetLabels = graphData.getLineSetLabels();
    boolean[] displayAlerts = graphData.displayAlerts();
    boolean[] displaySeverityAlerts = graphData.displaySeverityAlerts();
    double[] lineSymbolSizes = graphData.getLineSymbolSizes();
    Color[] graphBaseColors = graphData.getGraphBaseColors();
    int displayKeyIndex = 0;
    double maxCount = 0;
    boolean singleAlertLegend = graphData.getShowSingleAlertLegend();
    boolean singleSeverityLegend = graphData.getShowSingleSeverityLegend();

    for (int i = 0; i < counts.length; i++) {
        String lineSetLabel = "series" + (i + 1);
        boolean displayAlert = false;
        boolean displaySeverityAlert = false;
        double lineSymbolSize = 7.0;
        try {
            lineSetLabel = lineSetLabels[i];
        } catch (Exception e) {
        }
        try {
            displayAlert = displayAlerts[i];
        } catch (Exception e) {
        }
        try {
            displaySeverityAlert = displaySeverityAlerts[i];
        } catch (Exception e) {
        }
        try {
            lineSymbolSize = lineSymbolSizes[i];
        } catch (Exception e) {
        }

        double xy = lineSymbolSize / 2.0 * -1;
        Color seriesColor = graphBaseColors[i % graphBaseColors.length];
        boolean displayNormalData = displaySeries(displayKey, displayKeyIndex++) ? true : false;
        boolean displayWarningData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true
                : false;
        boolean displayAlertData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false;
        boolean displaySevereData = displaySeverityAlert && displaySeries(displayKey, displayKeyIndex++) ? true
                : false;
        List<DataPoint> points = new ArrayList<DataPoint>();

        /** get graph data */

        for (int j = 0; j < counts[i].length; j++) {
            boolean alertDataExists = false;
            String altText = null;
            String lineSetURL = null;
            int color = 1;
            try {
                altText = altTexts[i][j];
            } catch (Exception e) {
            }
            try {
                lineSetURL = lineSetURLs[i][j];
            } catch (Exception e) {
            }
            try {
                color = colors[i][j];
            } catch (Exception e) {
            }

            Map<String, Object> pointMetaData = new HashMap<String, Object>();
            pointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText);
            pointMetaData.put(GraphSource.ITEM_URL, lineSetURL);
            pointMetaData.put(GraphSource.ITEM_SHAPE,
                    new Ellipse2D.Double(xy, xy, lineSymbolSize, lineSymbolSize));

            pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor);

            // color 0 = GRAY (no data), color 2 = YELLOW (warning), 3 = RED (alert),
            // 4 = PURPLE (severe)
            if (useNoDataColor && color == 0) {
                pointMetaData.put(GraphSource.ITEM_COLOR, noDataColor);
            } else if (displayWarningData && color == 2) {
                alertDataExists = true;
                pointMetaData.put(GraphSource.ITEM_COLOR, warningDataColor);
            } else if (displayAlertData && color == 3) {
                alertDataExists = true;
                pointMetaData.put(GraphSource.ITEM_COLOR, alertDataColor);
            } else if (displaySevereData && color == 4) {
                alertDataExists = true;
                pointMetaData.put(GraphSource.ITEM_COLOR, severeDataColor);
            }

            if (useItemColor) {
                seriesColor = graphBaseColors[j % graphBaseColors.length];
                pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor);
            }

            if (displayNormalData || alertDataExists) {
                // only update the maxCount if this data point is visible
                if (counts[i][j] > maxCount) {
                    maxCount = counts[i][j];
                }
            } else {
                // if normal data is supposed to be hidden and no alert data exists, then hide this
                // data point
                pointMetaData.put(GraphSource.ITEM_VISIBLE, false);
            }

            // if the data is set to the Double.MIN_VALUE, then add it as a null.
            if (counts[i][j] != Double.MIN_VALUE) {
                points.add(new DataPoint(counts[i][j], xLabels[j], pointMetaData));
            } else {
                points.add(new DataPoint(null, xLabels[j], pointMetaData));
            }

        }

        /** add the series */

        // series properties
        Map<String, Object> dataSeriesMetaData = new HashMap<String, Object>();
        dataSeriesMetaData.put(GraphSource.SERIES_TITLE, lineSetLabel);
        dataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor);
        // if normal data is hidden for this series, hide the series connector line
        dataSeriesMetaData.put(GraphSource.SERIES_LINES_VISIBLE, displayNormalData);
        dataSeries.add(new DataSeries(points, dataSeriesMetaData));

        if (legendItems != null) {
            if (displayNormalData && legendItems.getItemCount() < maxLegendItems) {
                if (displayAlert && !singleAlertLegend) {
                    legendItems
                            .add(new LegendItem(lineSetLabel + ": " + getTranslation("Normal"), seriesColor));
                } else {
                    legendItems.add(new LegendItem(lineSetLabel, seriesColor));
                }
            }
            if (!singleAlertLegend && displayWarningData && legendItems.getItemCount() < maxLegendItems) {
                legendItems
                        .add(new LegendItem(lineSetLabel + ": " + getTranslation("Warning"), warningDataColor));
            }
            if (!singleAlertLegend && displayAlertData && legendItems.getItemCount() < maxLegendItems) {
                legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Alert"), alertDataColor));
            }
            if (!singleSeverityLegend && displaySevereData && legendItems.getItemCount() < maxLegendItems) {
                legendItems
                        .add(new LegendItem(lineSetLabel + ": " + getTranslation("Severe"), severeDataColor));
            }
        }
    }

    if (singleAlertLegend && legendItems.getItemCount() < maxLegendItems) {
        legendItems.add(new LegendItem(getTranslation("Warning"), warningDataColor));
        legendItems.add(new LegendItem(getTranslation("Alert"), alertDataColor));
    }
    if (singleSeverityLegend && legendItems.getItemCount() < maxLegendItems) {
        legendItems.add(new LegendItem(getTranslation("Severe"), severeDataColor));
    }
    return maxCount;
}

From source file:gov.llnl.lustre.lwatch.PlotFrame2.java

/**
 * Define the JFreeChart chart.//from  ww w  .j  av a 2 s.c  o m
 *
 * @param dataset dataset to be plotted in the chart.
 */

public JFreeChart createChart(XYDataset dataset) {

    // Load data for settings from last "Refresh" time
    String[] selectedRows = lastRefreshPlotParams.getCategories();
    String[] selectedVars = lastRefreshPlotParams.getVariables();
    String[] selectedCurves = lastRefreshPlotParams.getCurves();

    int savedGranularity = granularity;
    granularity = lastRefreshPlotParams.getGranularity();

    boolean showLegend = true;
    //if (((isAnAggPlot) && (nColsSelected * nCurvesSelected > 8)) ||
    //(nRowsSelected * nColsSelected * nCurvesSelected > 8))
    //showLegend = false;
    if (((isAnAggPlot) && (selectedVars.length * selectedCurves.length > 8))
            || (selectedRows.length * selectedVars.length * selectedCurves.length > 8))
        showLegend = false;

    //if (fromRefresh && (nRowsSelected > 0 && nColsSelected > 0 && nCurvesSelected > 0) &&
    //(!noVarSelected)) {
    if (fromRefresh && (selectedRows.length > 0 && selectedVars.length > 0 && selectedCurves.length > 0)
            && (!noVarSelected)) {
        //Debug.out("nRowsSelected = " + nRowsSelected +
        //"   nColsSelected = " + nColsSelected +
        //"   nCurvesSelected = " + nCurvesSelected);

        pD = new PlotDescriptor();
    }

    chart = ChartFactory.createTimeSeriesChart(fsName + " - " + type + " data", // title
            "Date", // x-axis label
            yAxisLabel, // y-axis label
            dataset, // data
            showLegend, // create legend
            false, // generate tooltips
            false // generate URLs
    );

    chart.setBackgroundPaint(Color.black); //white);  // Border color
    chart.setBorderVisible(true);
    TextTitle tTitle = chart.getTitle();
    tTitle.setPaint(Color.white);

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.black); //lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainCrosshairVisible(false);
    plot.setRangeCrosshairVisible(false);

    // Check need for logorihmic axis
    if (useLogRangeAxis) {
        LogarithmicAxis rangeAxis2 = new LogarithmicAxis(yAxisLabel);
        plot.setRangeAxis(0, rangeAxis2);
    }

    // Default axis annotation is in black. So if the chart background
    // Paint was set to black above, we need to set axis labels, 
    // tick labels and tick marks to be a contrasting color.
    plot.getDomainAxis().setLabelPaint(Color.white);
    plot.getDomainAxis().setTickLabelPaint(Color.white);
    plot.getDomainAxis().setTickMarkPaint(Color.white);
    plot.getRangeAxis().setLabelPaint(Color.white);
    plot.getRangeAxis().setTickLabelPaint(Color.white);
    plot.getRangeAxis().setTickMarkPaint(Color.white);

    // Grab the colors from the legend.
    //int nCurves = nRowsSelected * nColsSelected * nCurvesSelected;
    int nCurves = selectedRows.length * selectedVars.length * selectedCurves.length;
    if (localDebug) {
        Debug.out("selectedRows.length, selectedVars.length, selectedCurves.length = " + selectedRows.length
                + ", " + selectedVars.length + ", " + selectedCurves.length);
        Debug.out("Dimension legendColors to size = " + nCurves);
    }
    legendColors = new Color[nCurves];
    LegendItemCollection lic = plot.getLegendItems();
    for (int i = 0; i < lic.getItemCount(); i++) {
        LegendItem li = lic.get(i);
        legendColors[i] = (Color) li.getLinePaint();
        //if (localDebug)
        //Debug.out("Line Paint for legend " + i + " = " +
        //legendColors[i]);
    }

    XYItemRenderer r = plot.getRenderer();
    if (r instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
        renderer.setBaseShapesVisible(showIcons); // Controls icons at data pts.
        renderer.setBaseShapesFilled(false);
    }

    DateAxis axis = (DateAxis) plot.getDomainAxis();
    if (granularity == Database.HOUR)
        axis.setDateFormatOverride(new SimpleDateFormat("MM/dd HH")); //("dd-MMM-yy"));
    else if (granularity == Database.DAY)
        axis.setDateFormatOverride(new SimpleDateFormat("MM/dd/yy")); //("dd-MMM-yy"));
    else if (granularity == Database.WEEK)
        axis.setDateFormatOverride(new SimpleDateFormat("MM/dd/yy")); //("dd-MMM-yy"));
    else if (granularity == Database.MONTH)
        axis.setDateFormatOverride(new SimpleDateFormat("MM/yy")); //("dd-MMM-yy"));
    else if (granularity == Database.YEAR)
        axis.setDateFormatOverride(new SimpleDateFormat("yyyy HH:mm")); //("dd-MMM-yy"));
    else // granualrity == Database.RAW or HEARTBEAT
        axis.setDateFormatOverride(new SimpleDateFormat("MM/dd HH:mm:ss")); //("dd-MMM-yy"));

    // Reset granularity;
    granularity = savedGranularity;

    return chart;

}