Example usage for org.jfree.data.xy XYSeriesCollection getSeriesCount

List of usage examples for org.jfree.data.xy XYSeriesCollection getSeriesCount

Introduction

In this page you can find the example usage for org.jfree.data.xy XYSeriesCollection getSeriesCount.

Prototype

@Override
public int getSeriesCount() 

Source Link

Document

Returns the number of series in the collection.

Usage

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

protected void formatConvexHullPlot(PlotJob job, JFreeChart chart, XYSeriesCollection dataSet1,
        XYSeriesCollection dataSet2) {/* w w  w  . j  a v  a 2s .com*/
    XYPlot plot = (XYPlot) chart.getPlot();
    XYLineAndShapeRenderer renderer1 = (XYLineAndShapeRenderer) plot.getRenderer();
    BasicStroke wideLine = new BasicStroke(2.0f);

    //For Scientific notation
    NumberFormat formatter = new DecimalFormat("0.######E0");

    for (int i = 0; i < plot.getDomainAxisCount(); i++) {
        plot.getDomainAxis(i).setLabelFont(new Font("SansSerif", Font.PLAIN, job.fontSize));
        plot.getDomainAxis(i).setTickLabelFont(new Font("SansSerif", Font.PLAIN, 15));
        plot.getDomainAxis(i).setLabelPaint(job.bgColor == Color.red ? Color.white : Color.black);
        plot.getDomainAxis(i).setTickLabelPaint(job.bgColor == Color.red ? Color.white : Color.black);
    }
    for (int i = 0; i < plot.getRangeAxisCount(); i++) {
        plot.getRangeAxis(i).setLabelFont(new Font("SansSerif", Font.PLAIN, job.fontSize));
        plot.getRangeAxis(i).setTickLabelFont(new Font("SansSerif", Font.PLAIN, 15));
        plot.getRangeAxis(i).setLabelPaint(job.bgColor == Color.red ? Color.white : Color.black);
        plot.getRangeAxis(i).setTickLabelPaint(job.bgColor == Color.red ? Color.white : Color.black);
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(i);
        rangeAxis.setNumberFormatOverride(formatter);
    }

    //White background outside of plottable area
    chart.setBackgroundPaint(job.bgColor);

    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.black);
    plot.setRangeGridlinePaint(Color.black);

    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    chart.getLegend().setItemFont(new Font("SansSerif", Font.PLAIN, 15));
    chart.getTitle().setFont(new Font("SansSerif", Font.PLAIN, job.fontSize));
    chart.getTitle().setPaint(job.bgColor == Color.red ? Color.white : Color.black);

    //If there is only one Y axis, color all datasets red (so top, bottom, left, and right will be the same)
    if (job.Y2headers == null || job.Y2headers.isEmpty()) {
        for (int i = 0; i < dataSet1.getSeriesCount(); i++) {
            renderer1.setSeriesStroke(i, wideLine);
            renderer1.setBaseShapesVisible(false);
            renderer1.setSeriesFillPaint(i, Color.red);
            renderer1.setSeriesPaint(i, Color.red);
            if (dataSet1.getSeries(i).getKey() != null
                    && dataSet1.getSeries(i).getKey().toString().equalsIgnoreCase("REMOVE"))
                renderer1.setSeriesVisibleInLegend(i, false);
        }
    }
    //If there are 2 Y axes, we should color the axes to correspond with the data so it isn't (as) confusing
    else {
        StandardXYItemRenderer renderer2 = new StandardXYItemRenderer();
        plot.setRenderer(1, renderer2);

        for (int i = 0; i < dataSet1.getSeriesCount(); i++) {
            renderer1.setSeriesStroke(i, wideLine);
            renderer1.setBaseShapesVisible(false);
            renderer1.setSeriesFillPaint(i, Color.red);
            renderer1.setSeriesPaint(i, Color.red);
            if (dataSet1.getSeries(i).getKey() != null
                    && dataSet1.getSeries(i).getKey().toString().equalsIgnoreCase("REMOVE"))
                renderer1.setSeriesVisibleInLegend(i, false);
        }
        for (int i = 0; i < dataSet2.getSeriesCount(); i++) {
            renderer2.setSeriesStroke(i, wideLine);
            renderer2.setBaseShapesVisible(false);
            renderer2.setSeriesFillPaint(i, Color.blue);
            renderer2.setSeriesPaint(i, Color.blue);
            if (dataSet2.getSeries(i).getKey() != null
                    && dataSet2.getSeries(i).getKey().toString().equalsIgnoreCase("REMOVE"))
                renderer2.setSeriesVisibleInLegend(i, false);
        }
        plot.getRangeAxis(0).setLabelPaint(Color.red);
        plot.getRangeAxis(0).setTickLabelPaint(Color.red);
        plot.getRangeAxis(1).setLabelPaint(Color.blue);
        plot.getRangeAxis(1).setTickLabelPaint(Color.blue);
    }
}

From source file:com.mothsoft.alexis.web.ChartServlet.java

private void doLineGraph(final HttpServletRequest request, final HttpServletResponse response,
        final String title, final String[] dataSetIds, final Integer width, final Integer height,
        final Integer numberOfSamples) throws ServletException, IOException {

    final DataSetService dataSetService = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext()).getBean(DataSetService.class);

    final OutputStream out = response.getOutputStream();
    response.setContentType("image/png");
    response.setHeader("Cache-Control", "max-age: 5; must-revalidate");

    final XYSeriesCollection seriesCollection = new XYSeriesCollection();

    final DateAxis dateAxis = new DateAxis(title != null ? title : "Time");
    final DateTickUnit unit = new DateTickUnit(DateTickUnit.HOUR, 1);
    final DateFormat chartFormatter = new SimpleDateFormat("ha");
    dateAxis.setDateFormatOverride(chartFormatter);
    dateAxis.setTickUnit(unit);/*from ww w  .  j a  va  2s  .c  o m*/
    dateAxis.setLabelFont(DEFAULT_FONT);
    dateAxis.setTickLabelFont(DEFAULT_FONT);

    if (numberOfSamples > 12) {
        dateAxis.setTickLabelFont(
                new Font(DEFAULT_FONT.getFamily(), Font.PLAIN, (int) (DEFAULT_FONT.getSize() * .8)));
    }

    final NumberAxis yAxis = new NumberAxis("Activity");

    final StandardXYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES_AND_LINES);

    int colorCounter = 0;

    if (dataSetIds != null) {
        for (final String dataSetIdString : dataSetIds) {
            final Long dataSetId = Long.valueOf(dataSetIdString);
            final DataSet dataSet = dataSetService.get(dataSetId);

            // go back for numberOfSamples, but include current hour
            final Calendar calendar = new GregorianCalendar();
            calendar.add(Calendar.HOUR_OF_DAY, -1 * (numberOfSamples - 1));
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            final Timestamp startDate = new Timestamp(calendar.getTimeInMillis());

            calendar.add(Calendar.HOUR_OF_DAY, numberOfSamples);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            final Timestamp endDate = new Timestamp(calendar.getTimeInMillis());

            logger.debug(String.format("Generating chart for period: %s to %s", startDate.toString(),
                    endDate.toString()));

            final List<DataSetPoint> dataSetPoints = dataSetService
                    .findAndAggregatePointsGroupedByUnit(dataSetId, startDate, endDate, TimeUnits.HOUR);

            final boolean hasData = addSeries(seriesCollection, dataSet.getName(), dataSetPoints, startDate,
                    numberOfSamples, renderer);

            if (dataSet.isAggregate()) {
                renderer.setSeriesPaint(seriesCollection.getSeriesCount() - 1, Color.BLACK);
            } else if (hasData) {
                renderer.setSeriesPaint(seriesCollection.getSeriesCount() - 1,
                        PAINTS[colorCounter++ % PAINTS.length]);
            } else {
                renderer.setSeriesPaint(seriesCollection.getSeriesCount() - 1, Color.LIGHT_GRAY);
            }
        }
    }

    final XYPlot plot = new XYPlot(seriesCollection, dateAxis, yAxis, renderer);

    // create the chart...
    final JFreeChart chart = new JFreeChart(plot);

    // set the background color for the chart...
    chart.setBackgroundPaint(Color.white);

    // get a reference to the plot for further customisation...
    plot.setBackgroundPaint(new Color(253, 253, 253));
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

    // set the range axis to display integers only...
    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setLabelFont(DEFAULT_FONT);
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setLowerBound(0.00d);

    ChartUtilities.writeChartAsPNG(out, chart, width, height);
}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.ChartUIComponent.java

/***********************************************************************************************
 * Update the existing Chart referenced by the DAO, by applying the specified datasets,
 * using all existing channel selections and range selections.
 * This implementation ASSUMES a ChannelSelector is present.
 *
 * @param dao// w  ww . j ava  2  s .co m
 * @param datasettype
 * @param primarydataset
 * @param secondarydatasets
 * @param displaylimit
 * @param domainstartpoint
 * @param domainendpoint
 * @param channelselector
 * @param debug
 */

public void updateChartForSelection(final ObservatoryInstrumentDAOInterface dao, final DatasetType datasettype,
        final XYDataset primarydataset, final List<XYDataset> secondarydatasets, final int displaylimit,
        final int domainstartpoint, final int domainendpoint,
        final ChannelSelectorUIComponentInterface channelselector, final boolean debug) {
    final String SOURCE = "ChartUIComponent.updateChartForSelection() ";

    if ((dao != null) && (dao.getChartUI() != null) && (dao.getChartUI().getChartPanel() != null)
            && (dao.getChartUI().getChartPanel().getChart() != null)
            && (dao.getChartUI().getChartPanel().getChart().getXYPlot() != null) && (datasettype != null)
            && (primarydataset != null) && (secondarydatasets != null) && (channelselector != null)) {
        final XYDataset xyNewPrimaryDataset;
        final List<XYDataset> listNewSecondaryDatasets;
        final List<XYDataset> listParentSecondaryDatasetForSeries;
        final Iterator iterOriginalSecondaryDatasets;
        final Calendar calObservatory;

        // Either find the Current Observatory calendar, or provide a default
        calObservatory = ObservatoryInstrumentHelper.getCurrentObservatoryCalendar(REGISTRY.getFramework(), dao,
                debug);

        // Create a list of NewSecondaryDatasets for display
        // Add an appropriate *empty* new dataset for every one existing in the secondary set
        // and record the parent new Dataset for each Series in each original Dataset
        // So much complexity just to handle the very few cases of secondary datasets...

        listNewSecondaryDatasets = new ArrayList<XYDataset>(10);
        listParentSecondaryDatasetForSeries = new ArrayList<XYDataset>(10);

        iterOriginalSecondaryDatasets = secondarydatasets.iterator();

        while (iterOriginalSecondaryDatasets.hasNext()) {
            final XYDataset xyDatasetOriginal;

            xyDatasetOriginal = (XYDataset) iterOriginalSecondaryDatasets.next();

            if ((xyDatasetOriginal != null) && (xyDatasetOriginal.getSeriesCount() > 0)) {
                final XYDataset xyDatasetNew;

                // Create an empty Dataset to correspond with the original
                if (datasettype.getName().equals(DatasetType.XY.getName())) {
                    xyDatasetNew = new XYSeriesCollection();
                    listNewSecondaryDatasets.add(xyDatasetNew);
                } else if (datasettype.getName().equals(DatasetType.TIMESTAMPED.getName())) {
                    xyDatasetNew = new TimeSeriesCollection(calObservatory.getTimeZone());
                    listNewSecondaryDatasets.add(xyDatasetNew);
                } else {
                    xyDatasetNew = new XYSeriesCollection();
                    listNewSecondaryDatasets.add(xyDatasetNew);
                }

                // Record the *same* parent Dataset for each Series in each original Secondary Dataset
                // This creates a List in channel order, but with references to Datasets not Series
                for (int i = 0; i < xyDatasetOriginal.getSeriesCount(); i++) {
                    listParentSecondaryDatasetForSeries.add(xyDatasetNew);
                }
            }
        }

        // Confirm the DatasetType
        if ((datasettype.getName().equals(DatasetType.XY.getName()))
                && (primarydataset instanceof XYSeriesCollection)) {
            final XYSeriesCollection collectionPrimary;

            // Prepare a new XYSeriesCollection for display
            xyNewPrimaryDataset = new XYSeriesCollection();

            // There should be a collection of <channelcount> XYSeries in the Primary Dataset
            // but there may also be some in the Secondary Datasets
            collectionPrimary = (XYSeriesCollection) primarydataset;

            // ToDo Make this work for ChannelSelector NULL, get channel count from primary and secondaries? Set mode to X1?

            if ((collectionPrimary.getSeriesCount() > 0) && (collectionPrimary.getSeries() != null)
                    && (channelselector.getChannelSelectionModes() != null)) {
                LOGGER.debug(debug, SOURCE + "XY domainstartpoint=" + domainstartpoint + " domainendpoint="
                        + domainendpoint);

                ChartHelper.dumpXYDataset(debug, calObservatory, collectionPrimary, 4,
                        SOURCE + "XYSeriesCollection --> Original Dataset");

                // Find which channels and data range to use this time round
                for (int intChannelIndex = 0; intChannelIndex < channelselector.getChannelSelectionModes()
                        .size(); intChannelIndex++) {
                    final ChannelSelectionMode selectionMode;

                    selectionMode = channelselector.getChannelSelectionModes().get(intChannelIndex);

                    if (!ChannelSelectionMode.OFF.equals(selectionMode)) {
                        final XYSeries seriesOriginalData;

                        // We needed to know about the secondary datasets in order to get the correct index
                        seriesOriginalData = (XYSeries) ChartHelper.getSeriesForIndex(datasettype,
                                primarydataset, secondarydatasets, intChannelIndex, debug);
                        if (seriesOriginalData != null) {
                            final XYSeries seriesChangedData;
                            final List listOriginalDataItems;
                            int intStartIndex;
                            int intEndIndex;

                            listOriginalDataItems = seriesOriginalData.getItems();

                            // Prepare a new Series for the changed data, with the same Key
                            seriesChangedData = new XYSeries(seriesOriginalData.getKey());

                            if (listOriginalDataItems.size() > 0) {
                                // Map the slider values to data indexes
                                intStartIndex = ChartHelper.transformDomainSliderValueToSeriesIndex(
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainstartpoint,
                                        DatasetDomainUIComponentInterface.INDEX_LEFT,
                                        collectionPrimary.getDomainLowerBound(true),
                                        collectionPrimary.getDomainUpperBound(true), DatasetType.XY,
                                        calObservatory, seriesOriginalData, debug);

                                intEndIndex = ChartHelper.transformDomainSliderValueToSeriesIndex(
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainendpoint,
                                        DatasetDomainUIComponentInterface.INDEX_RIGHT,
                                        collectionPrimary.getDomainLowerBound(true),
                                        collectionPrimary.getDomainUpperBound(true), DatasetType.XY,
                                        calObservatory, seriesOriginalData, debug);
                                if ((intStartIndex == -1) || (intEndIndex == -1)) {
                                    // If either index is returned as -1, then there's nothing to do...
                                    // ...so stop the for() loop
                                    intStartIndex = 0;
                                    intEndIndex = 0;
                                } else if (intEndIndex <= intStartIndex) {
                                    intEndIndex = intStartIndex + 1;
                                }

                                LOGGER.debug(debug,
                                        SOURCE + "before copy of selected series subset [channel="
                                                + intChannelIndex + "] [index.start=" + intStartIndex
                                                + "] [index.end=" + intEndIndex + "]");

                                // Copy over only the selected range from the Slider
                                for (int intDataIndex = intStartIndex; intDataIndex < intEndIndex; intDataIndex++) {
                                    final XYDataItem dataOriginalItem;
                                    final XYDataItem dataChangedItem;

                                    dataOriginalItem = (XYDataItem) listOriginalDataItems.get(intDataIndex);

                                    if (!ChannelSelectionMode.X1.equals(selectionMode)) {
                                        // Change each value of the series according to the multiplier
                                        dataChangedItem = new XYDataItem(dataOriginalItem.getX(),
                                                dataOriginalItem.getY().doubleValue()
                                                        * selectionMode.getMultiplier());
                                    } else {
                                        // Just use the whole series unaltered for gain of X1
                                        dataChangedItem = new XYDataItem(dataOriginalItem.getX(),
                                                dataOriginalItem.getY());
                                    }

                                    seriesChangedData.add(dataChangedItem);
                                }

                                // Did we collect any data for this Series?
                                // If not, place a dummy point at the origin of the *visible* chart
                                if (seriesChangedData.getItemCount() == 0) {
                                    // TODO ChartHelper.createDummyXYSeriesDataItemAtOrigin()
                                    seriesChangedData.add(new XYDataItem(0, 0));
                                }

                                // Place the changed series in the correct collection
                                // to correspond with the original
                                if (intChannelIndex < collectionPrimary.getSeriesCount()) {
                                    // Simply add the changed Primary series to the PrimaryDataset collection
                                    ((XYSeriesCollection) xyNewPrimaryDataset).addSeries(seriesChangedData);
                                } else {
                                    // It must be a secondary dataset
                                    // Add the changed Secondary series to the parent SecondaryDataset
                                    // given by the *secondary* channel index
                                    ChartHelper.addSecondarySeries(datasettype,
                                            listParentSecondaryDatasetForSeries, seriesChangedData,
                                            intChannelIndex - collectionPrimary.getSeriesCount());
                                }
                            } else {
                                LOGGER.warn(SOURCE + "OriginalData XYSeries unexpectedly NULL");
                            }
                        } else {
                            // There are no data! Do nothing...
                            LOGGER.warn(SOURCE + "There are no data, so do nothing");
                        }
                    }
                }

                LOGGER.debug(debug, SOURCE + "Update the data shown on existing Chart");

                // The outputs are xyNewPrimaryDataset and listNewSecondaryDatasets
                // This Chart does not use secondary datasets (yet)

                // Dump the (partial) contents of each Series in the new XYdataset
                ChartHelper.dumpXYDataset(debug, calObservatory, xyNewPrimaryDataset, 4,
                        SOURCE + "XYSeriesCollection --> setDataset");

                dao.getChartUI().getChartPanel().getChart().getXYPlot().setDataset(INDEX_DATA,
                        xyNewPrimaryDataset);
            } else {
                LOGGER.error(SOURCE + " The XYSeriesCollection does not have any XYSeries");
            }
        } else if ((datasettype.getName().equals(DatasetType.TIMESTAMPED.getName()))
                && (primarydataset instanceof TimeSeriesCollection)) {
            final TimeSeriesCollection collectionPrimary;

            LOGGER.debug(debug, SOURCE + "TIMESTAMPED domainstartpoint=" + domainstartpoint + " domainendpoint="
                    + domainendpoint);

            // Prepare a new TimeSeriesCollection for display
            xyNewPrimaryDataset = new TimeSeriesCollection(calObservatory.getTimeZone());

            // There should be a collection of <channelcount> TimeSeries in the Primary Dataset
            // but there may also be some in the Secondary Datasets
            collectionPrimary = (TimeSeriesCollection) primarydataset;

            if ((collectionPrimary.getSeriesCount() > 0) && (collectionPrimary.getSeries() != null)
                    && (channelselector.getChannelSelectionModes() != null)) {
                ChartHelper.dumpXYDataset(debug, calObservatory, collectionPrimary, 4,
                        SOURCE + "TimeSeriesCollection PrimaryDataset --> Original Dataset");

                // Find which channels and data range to use this time round
                for (int intChannelIndex = 0; intChannelIndex < channelselector.getChannelSelectionModes()
                        .size(); intChannelIndex++) {
                    final ChannelSelectionMode selectionMode;

                    selectionMode = channelselector.getChannelSelectionModes().get(intChannelIndex);

                    if (!ChannelSelectionMode.OFF.equals(selectionMode)) {
                        final TimeSeries seriesOriginalData;

                        // We needed to know about the secondary datasets in order to get the correct index
                        seriesOriginalData = (TimeSeries) ChartHelper.getSeriesForIndex(datasettype,
                                primarydataset, secondarydatasets, intChannelIndex, debug);
                        if (seriesOriginalData != null) {
                            final List listOriginalDataItems;
                            final TimeSeries seriesChangedData;

                            listOriginalDataItems = seriesOriginalData.getItems();

                            // Prepare a new Series for the changed data, with the same Key
                            seriesChangedData = new TimeSeries(seriesOriginalData.getKey().toString(),
                                    seriesOriginalData.getTimePeriodClass());

                            if (listOriginalDataItems.size() > 0) {
                                int intStartIndex;
                                int intEndIndex;

                                // Map the slider values to data indexes
                                intStartIndex = ChartHelper.transformDomainSliderValueToSeriesIndex(
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainstartpoint,
                                        DatasetDomainUIComponentInterface.INDEX_LEFT,
                                        collectionPrimary.getDomainLowerBound(true),
                                        collectionPrimary.getDomainUpperBound(true), DatasetType.TIMESTAMPED,
                                        calObservatory, seriesOriginalData, debug);

                                intEndIndex = ChartHelper.transformDomainSliderValueToSeriesIndex(
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                        ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainendpoint,
                                        DatasetDomainUIComponentInterface.INDEX_RIGHT,
                                        collectionPrimary.getDomainLowerBound(true),
                                        collectionPrimary.getDomainUpperBound(true), DatasetType.TIMESTAMPED,
                                        calObservatory, seriesOriginalData, debug);
                                if ((intStartIndex == -1) || (intEndIndex == -1)) {
                                    // If either index is returned as -1, then there's nothing to do...
                                    // ...so stop the for() loop
                                    LOGGER.debug(debug, SOURCE + "Set EndIndex = StartIndex = 0");
                                    intStartIndex = 0;
                                    intEndIndex = 0;
                                } else if (intEndIndex <= intStartIndex) {
                                    LOGGER.debug(debug, SOURCE + "Correcting EndIndex less than StartIndex");
                                    intEndIndex = intStartIndex + 1;
                                }

                                LOGGER.debug(debug,
                                        SOURCE + "before copy of selected series subset [channel="
                                                + intChannelIndex + "] [start_index=" + intStartIndex
                                                + "] [end_index=" + intEndIndex + "]");

                                // Copy over only the selected range from the Slider
                                for (int intDataIndex = intStartIndex; intDataIndex < intEndIndex; intDataIndex++) {
                                    final TimeSeriesDataItem dataOriginalItem;
                                    final TimeSeriesDataItem dataChangedItem;

                                    dataOriginalItem = (TimeSeriesDataItem) listOriginalDataItems
                                            .get(intDataIndex);

                                    if (!ChannelSelectionMode.X1.equals(selectionMode)) {
                                        // Change each value of the series according to the multiplier
                                        dataChangedItem = new TimeSeriesDataItem(dataOriginalItem.getPeriod(),
                                                dataOriginalItem.getValue().doubleValue()
                                                        * selectionMode.getMultiplier());
                                    } else {
                                        // Just use the whole series unaltered for gain of X1
                                        dataChangedItem = new TimeSeriesDataItem(dataOriginalItem.getPeriod(),
                                                dataOriginalItem.getValue().doubleValue());
                                    }

                                    seriesChangedData.add(dataChangedItem);
                                }

                                // Did we collect any data for this Series?
                                // If not, place a dummy point at the origin of the *visible* chart
                                if (seriesChangedData.getItemCount() == 0) {
                                    seriesChangedData.add(ChartHelper.createDummyTimeSeriesDataItemAtOrigin(
                                            collectionPrimary, seriesOriginalData, domainstartpoint, debug));
                                }

                                // Place the changed series in the correct collection
                                // to correspond with the original
                                if (intChannelIndex < collectionPrimary.getSeriesCount()) {
                                    // Simply add the changed Primary series to the PrimaryDataset collection
                                    ((TimeSeriesCollection) xyNewPrimaryDataset).addSeries(seriesChangedData);
                                } else {
                                    // It must be a secondary dataset
                                    // Add the changed Secondary series to the parent SecondaryDataset
                                    // given by the *secondary* channel index
                                    ChartHelper.addSecondarySeries(datasettype,
                                            listParentSecondaryDatasetForSeries, seriesChangedData,
                                            intChannelIndex - collectionPrimary.getSeriesCount());
                                }
                            } else {
                                // There are no data! Do nothing...
                                LOGGER.warn(SOURCE + "There are no data, so do nothing [channel.index="
                                        + intChannelIndex + "]");
                            }
                        } else {
                            LOGGER.warn(SOURCE + "OriginalData TimeSeries unexpectedly NULL [channel.index="
                                    + intChannelIndex + "]");
                        }
                    } else {
                        LOGGER.debug(debug, SOURCE + "Channel is OFF [channel.index=" + intChannelIndex + "]");
                    }
                }

                LOGGER.debug(debug, SOURCE + "Update the data shown on existing Chart");

                // The outputs are xyNewPrimaryDataset and listNewSecondaryDatasets
                // This Chart superclass does not use secondary datasets (yet)

                // Dump the (partial) contents of each Series in the new XYdataset
                ChartHelper.dumpXYDataset(debug, calObservatory, xyNewPrimaryDataset, 4,
                        SOURCE + "TimeSeriesCollection NewPrimaryDataset --> setDataset");

                dao.getChartUI().getChartPanel().getChart().getXYPlot().setDataset(INDEX_DATA,
                        xyNewPrimaryDataset);
            } else {
                LOGGER.error(SOURCE + " The TimeSeriesCollection does not have any TimeSeries");
            }
        } else {
            LOGGER.error(SOURCE + " The Dataset is of an invalid type");
        }
    } else {
        LOGGER.debug(debug, SOURCE + " Unable to change the Chart - invalid parameters");
    }
}

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

protected void formatMultiPlot(PlotJob job, JFreeChart chart, XYSeriesCollection dataSet1,
        XYSeriesCollection dataSet2) {/*from   w w  w.j  a  v  a2s.co m*/
    Color[] blueColors = { Color.blue, Color.cyan, new Color(0, 160, 255), new Color(0, 100, 255),
            new Color(0, 160, 255), new Color(14, 0, 145), new Color(70, 105, 150) };
    Color[] redColors = { Color.red, Color.magenta, new Color(255, 0, 100), new Color(255, 0, 160), Color.pink,
            new Color(145, 0, 0), new Color(132, 58, 58) };
    Color[] variedColors = { Color.red, Color.blue, Color.green, Color.orange, Color.magenta, Color.cyan,
            Color.gray, new Color(255, 165, 0), new Color(42, 183, 136), new Color(87, 158, 186) };
    XYPlot plot = (XYPlot) chart.getPlot();
    XYLineAndShapeRenderer renderer1 = (XYLineAndShapeRenderer) plot.getRenderer();
    BasicStroke wideLine = new BasicStroke(2.0f);

    //For Scientific notation
    NumberFormat formatter = new DecimalFormat("0.######E0");

    for (int i = 0; i < plot.getDomainAxisCount(); i++) {
        plot.getDomainAxis(i).setLabelFont(new Font("SansSerif", Font.PLAIN, job.fontSize));
        plot.getDomainAxis(i).setTickLabelFont(new Font("SansSerif", Font.PLAIN, 15));
        plot.getDomainAxis(i).setLabelPaint(job.bgColor == Color.red ? Color.white : Color.black);
        plot.getDomainAxis(i).setTickLabelPaint(job.bgColor == Color.red ? Color.white : Color.black);
    }
    for (int i = 0; i < plot.getRangeAxisCount(); i++) {
        plot.getRangeAxis(i).setLabelFont(new Font("SansSerif", Font.PLAIN, job.fontSize));
        plot.getRangeAxis(i).setTickLabelFont(new Font("SansSerif", Font.PLAIN, 15));
        plot.getRangeAxis(i).setLabelPaint(job.bgColor == Color.red ? Color.white : Color.black);
        plot.getRangeAxis(i).setTickLabelPaint(job.bgColor == Color.red ? Color.white : Color.black);
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(i);
        rangeAxis.setNumberFormatOverride(formatter);
    }

    //White background outside of plottable area
    chart.setBackgroundPaint(job.bgColor);

    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.black);
    plot.setRangeGridlinePaint(Color.black);

    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    chart.getLegend().setItemFont(new Font("SansSerif", Font.PLAIN, 15));
    chart.getTitle().setFont(new Font("SansSerif", Font.PLAIN, job.fontSize));
    chart.getTitle().setPaint(job.bgColor == Color.red ? Color.white : Color.black);

    //If there is only one Y axis, we just need to color the data series differently
    if (job.Y2headers == null || job.Y2headers.isEmpty()) {
        for (int i = 0, cIndex = 0; i < dataSet1.getSeriesCount(); i++, cIndex++) {
            renderer1.setSeriesStroke(i, wideLine);
            renderer1.setBaseShapesVisible(false);
            if (cIndex > 9)
                cIndex = 0;
            renderer1.setSeriesFillPaint(i, variedColors[cIndex]);
            renderer1.setSeriesPaint(i, variedColors[cIndex]);
        }
    }
    //If there are 2 Y axes, we should color the axes to correspond with the data so it isn't (as) confusing
    else {
        StandardXYItemRenderer renderer2 = new StandardXYItemRenderer();
        plot.setRenderer(1, renderer2);

        for (int i = 0, cIndex = 0; i < dataSet1.getSeriesCount(); i++, cIndex++) {
            renderer1.setSeriesStroke(i, wideLine);
            renderer1.setBaseShapesVisible(false);
            if (cIndex > 6)
                cIndex = 0;
            renderer1.setSeriesFillPaint(i, redColors[cIndex]);
            renderer1.setSeriesPaint(i, redColors[cIndex]);
        }
        for (int i = 0, cIndex = 0; i < dataSet2.getSeriesCount(); i++, cIndex++) {
            renderer2.setSeriesStroke(i, wideLine);
            renderer2.setBaseShapesVisible(false);
            if (cIndex > 6)
                cIndex = 0;
            renderer2.setSeriesFillPaint(i, blueColors[cIndex]);
            renderer2.setSeriesPaint(i, blueColors[cIndex]);
        }
        plot.getRangeAxis(0).setLabelPaint(redColors[0]);
        plot.getRangeAxis(0).setTickLabelPaint(redColors[0]);
        plot.getRangeAxis(1).setLabelPaint(blueColors[0]);
        plot.getRangeAxis(1).setTickLabelPaint(blueColors[0]);
    }
}

From source file:dbseer.gui.chart.DBSeerChartFactory.java

public static JFreeChart createXYLinePredictionChart(PredictionCenter center) throws Exception {
    StatisticalPackageRunner runner = DBSeerGUI.runner;

    String title = runner.getVariableString("title");
    Object[] legends = (Object[]) runner.getVariableCell("legends");
    Object[] xCellArray = (Object[]) runner.getVariableCell("Xdata");
    Object[] yCellArray = (Object[]) runner.getVariableCell("Ydata");
    String xLabel = runner.getVariableString("Xlabel");
    String yLabel = runner.getVariableString("Ylabel");

    XYSeriesCollection dataSet = new XYSeriesCollection();

    int numLegends = legends.length;
    int numXCellArray = xCellArray.length;
    int numYCellArray = yCellArray.length;
    int dataCount = 0;

    if (numXCellArray != numYCellArray) {
        JOptionPane.showMessageDialog(null, "The number of X dataset and Y dataset does not match.",
                "The number of X dataset and Y dataset does not match.", JOptionPane.ERROR_MESSAGE);
        System.out.println(numXCellArray + " : " + numYCellArray);
        return null;
    }/*w  ww  . ja v  a2  s.  com*/

    final java.util.List<String> transactionNames = center.getTrainConfig().getDataset(0)
            .getTransactionTypeNames();
    for (int i = 0; i < numLegends; ++i) {
        String legend = (String) legends[i];
        for (int j = 0; j < transactionNames.size(); ++j) {
            if (legend.contains("Type " + (j + 1))) {
                legends[i] = legend.replace("Type " + (j + 1), transactionNames.get(j));
                break;
            }
        }
    }
    for (int j = 0; j < transactionNames.size(); ++j) {
        if (xLabel.contains("Type " + (j + 1))) {
            xLabel = xLabel.replace("Type " + (j + 1), transactionNames.get(j));
            break;
        }
    }
    for (int j = 0; j < transactionNames.size(); ++j) {
        if (yLabel.contains("Type " + (j + 1))) {
            yLabel = yLabel.replace("Type " + (j + 1), transactionNames.get(j));
            break;
        }
    }

    for (int i = 0; i < numYCellArray; ++i) {
        double[] xArray = (double[]) xCellArray[i];
        runner.eval("yArraySize = size(Ydata{" + (i + 1) + "});");
        runner.eval("yArray = Ydata{" + (i + 1) + "};");
        double[] yArraySize = runner.getVariableDouble("yArraySize");
        double[] yArray = runner.getVariableDouble("yArray");

        int xLength = xArray.length;
        int row = (int) yArraySize[0];
        int col = (int) yArraySize[1];

        for (int c = 0; c < col; ++c) {
            XYSeries series;
            int legendIdx = (dataCount >= numLegends) ? numLegends - 1 : dataCount;
            String legend = (String) legends[legendIdx];
            if (numLegends == 0) {
                series = new XYSeries("Data " + dataCount + 1);
            } else if (dataCount >= numLegends) {
                series = new XYSeries(legend + (dataCount + 1));
            } else {
                series = new XYSeries(legend);
            }

            for (int r = 0; r < row; ++r) {
                int xRow = (r >= xLength) ? xLength - 1 : r;
                double yValue = yArray[r + c * row];
                // remove negatives & NaN & infs.
                if (yValue < 0 || yValue == Double.NaN || yValue == Double.POSITIVE_INFINITY
                        || yValue == Double.NEGATIVE_INFINITY) {
                    yValue = 0.0;
                }
                series.add(xArray[xRow], yValue);
            }
            dataSet.addSeries(series);
            ++dataCount;
        }
    }

    JFreeChart chart = ChartFactory.createXYLineChart(title, xLabel, yLabel, dataSet);

    // change 'predicted' data to have dotted lines.
    BasicStroke dashStroke = toStroke(STYLE_DASH);
    BasicStroke dotStroke = toStroke(STYLE_DOT);
    BasicStroke lineStroke = toStroke(STYLE_LINE);
    for (int i = 0; i < dataSet.getSeriesCount(); ++i) {
        String legend = (String) dataSet.getSeriesKey(i);
        XYPlot plot = chart.getXYPlot();
        XYItemRenderer renderer = plot.getRenderer();
        if (legend.contains("predicted") || legend.contains("Predicted")) {
            renderer.setSeriesStroke(i, dotStroke);
        } else {
            renderer.setSeriesStroke(i, lineStroke);
        }
    }

    return chart;
}

From source file:com.naryx.tagfusion.cfm.tag.awt.cfCHART.java

private XYPlot getXYPlot(List<cfCHARTSERIESData> series, String xAxisTitle, String yAxisTitle,
        String labelFormat, boolean bShowMarkers, int markerSize, boolean bShow3D, String tipStyle,
        String drillDownUrl, int xOffset, int yOffset, int yAxisUnits, String seriesPlacement, int height,
        int gridLines) throws cfmRunTimeException {
    // Create an XY plot
    XYPlot plot = new XYPlot();
    ValueAxis domainAxis;//from  w ww . j  a v a2s. c  om

    if (series.get(0).getSeriesDataType() == cfCHARTSERIESData.XY_NUMERIC_SERIES) {
        if (bShow3D)
            domainAxis = new NumberAxis3D(xAxisTitle);
        else
            domainAxis = new NumberAxis(xAxisTitle);
    } else {
        domainAxis = new DateAxis(xAxisTitle);
    }
    plot.setDomainAxis(domainAxis);

    ValueAxis valueAxis;
    DateFormat dateFormat = null;
    NumberFormat numberFormat = null;
    if (labelFormat.equals("date")) {
        valueAxis = new DateAxis(yAxisTitle);
        dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        ((DateAxis) valueAxis).setDateFormatOverride(dateFormat);
    } else {
        if (bShow3D)
            valueAxis = new NumberAxis3D(yAxisTitle);
        else
            valueAxis = new NumberAxis(yAxisTitle);
        if (labelFormat.equals("currency")) {
            ((NumberAxis) valueAxis).setNumberFormatOverride(NumberFormat.getCurrencyInstance());
            numberFormat = NumberFormat.getCurrencyInstance();
        } else if (labelFormat.equals("percent")) {
            numberFormat = NumberFormat.getPercentInstance();
            numberFormat.setMaximumFractionDigits(3); // without this change .11443
                                                      // would be displayed as 11%
                                                      // instead of 11.443%
            ((NumberAxis) valueAxis).setNumberFormatOverride(numberFormat);
        } else {
            numberFormat = NumberFormat.getInstance();
        }

        if (yAxisUnits != 0)
            ((NumberAxis) valueAxis).setTickUnit(new NumberTickUnit(yAxisUnits));
    }
    plot.setRangeAxis(valueAxis);

    // Add a dataset and renderer for each series
    int barChartDatasetIndex = -1;
    int hBarChartDatasetIndex = -1;
    int num = 0;
    MinMaxData minMax = new MinMaxData();
    for (int i = 0; i < series.size(); i++) {
        cfCHARTSERIESData seriesData = series.get(i);
        XYSeriesCollection dataset;
        if ((barChartDatasetIndex != -1) && (seriesData.getType().equals("bar"))) {
            dataset = (XYSeriesCollection) plot.getDataset(barChartDatasetIndex);

            addSeriesDataToDataset(seriesData, dataset, minMax);

            // Set the paint style for this series
            setPaintStyle(seriesData.getPaintStyle(), plot.getRenderer(barChartDatasetIndex),
                    dataset.getSeriesCount() - 1, height);

            // Add the color list for this series to the custom color renderer
            CustomColorRenderer cr = (CustomColorRenderer) plot.getRenderer(barChartDatasetIndex);
            cr.addColors(getColorList(seriesData));

            continue;
        } else if ((hBarChartDatasetIndex != -1) && (seriesData.getType().equals("horizontalbar"))) {
            dataset = (XYSeriesCollection) plot.getDataset(hBarChartDatasetIndex);

            addSeriesDataToDataset(seriesData, dataset, minMax);

            // Set the paint style for this series
            setPaintStyle(seriesData.getPaintStyle(), plot.getRenderer(hBarChartDatasetIndex),
                    dataset.getSeriesCount() - 1, height);

            // Add the color list for this series to the custom color renderer
            CustomColorRenderer cr = (CustomColorRenderer) plot.getRenderer(hBarChartDatasetIndex);
            cr.addColors(getColorList(seriesData));

            continue;
        } else {
            dataset = new XYSeriesCollection();

            addSeriesDataToDataset(seriesData, dataset, minMax);
        }

        plot.setDataset(num, dataset);

        XYItemRenderer renderer = null;
        if (seriesData.getType().equals("bar")) {
            plot.setOrientation(PlotOrientation.VERTICAL);
            renderer = getXYBarRenderer(seriesPlacement, bShow3D, xOffset, yOffset, getColorList(seriesData));
            ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
                    TextAnchor.BOTTOM_CENTER);
            renderer.setPositiveItemLabelPosition(position1);
            ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6,
                    TextAnchor.TOP_CENTER);
            renderer.setNegativeItemLabelPosition(position2);
            ((XYBarRenderer) renderer).setMargin(0.2); // The margin between each
                                                       // category

            barChartDatasetIndex = num;
        } else if (seriesData.getType().equals("horizontalbar")) {
            plot.setOrientation(PlotOrientation.HORIZONTAL);
            plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
            renderer = getXYBarRenderer(seriesPlacement, bShow3D, xOffset, yOffset, getColorList(seriesData));
            ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3,
                    TextAnchor.CENTER_LEFT);
            renderer.setPositiveItemLabelPosition(position1);
            ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE9,
                    TextAnchor.CENTER_RIGHT);
            renderer.setNegativeItemLabelPosition(position2);
            ((XYBarRenderer) renderer).setMargin(0.2); // The margin between each
                                                       // category

            hBarChartDatasetIndex = num;
        } else if (seriesData.getType().equals("line")) {
            renderer = new XYLineAndShapeRenderer(true, false);

            // Enable/Disable displaying of markers
            ((XYLineAndShapeRenderer) renderer).setShapesVisible(bShowMarkers);

            // Set the shape of the markers based on the markerSize value
            ((XYLineAndShapeRenderer) renderer).setShape(getMarker(seriesData.getMarkerStyle(), markerSize));
        } else if (seriesData.getType().equals("area")) {
            renderer = new CustomXYAreaRenderer();
        } else if (seriesData.getType().equals("step")) {
            renderer = new CustomXYStepRenderer();
        } else if (seriesData.getType().equals("scatter")) {
            renderer = new XYLineAndShapeRenderer(false, true);

            // Set the shape of the markers based on the markerSize value
            ((XYLineAndShapeRenderer) renderer).setShape(getMarker(seriesData.getMarkerStyle(), markerSize));
        }

        if (!tipStyle.equals("none")) {
            if (series.get(0).getSeriesDataType() == cfCHARTSERIESData.XY_DATE_SERIES) {
                renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{0}: {1}",
                        DateFormat.getInstance(), DateFormat.getInstance()));
            } else {
                if (dateFormat != null)
                    renderer.setBaseToolTipGenerator(
                            new StandardXYToolTipGenerator("{0}: {2}", dateFormat, dateFormat));
                else
                    renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{0}: ({1}, {2})",
                            numberFormat, NumberFormat.getInstance()));
            }
        }

        if (drillDownUrl != null) {
            if (dateFormat != null)
                renderer.setURLGenerator(
                        new com.newatlanta.bluedragon.XYURLGenerator(drillDownUrl, dateFormat));
            else
                renderer.setURLGenerator(
                        new com.newatlanta.bluedragon.XYURLGenerator(drillDownUrl, numberFormat));
        }

        if (seriesData.getSeriesColor() != null)
            renderer.setSeriesPaint(0, convertStringToColor(seriesData.getSeriesColor()));

        String dataLabelStyle = seriesData.getDataLabelStyle();
        if (labelFormat.equals("date")) {
            if (dataLabelStyle.equals("none")) {
                renderer.setItemLabelsVisible(false);
            } else {
                setXYItemLabelsData(renderer, seriesData);
                if (dataLabelStyle.equals("value"))
                    renderer.setItemLabelGenerator(
                            new StandardXYItemLabelGenerator("{2}", dateFormat, dateFormat));
                else if (dataLabelStyle.equals("rowlabel"))
                    renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator("{0}",
                            NumberFormat.getInstance(), NumberFormat.getInstance()));
                else if (dataLabelStyle.equals("columnlabel"))
                    renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator("{1}",
                            NumberFormat.getInstance(), NumberFormat.getInstance()));
                else if (dataLabelStyle.equals("pattern"))
                    renderer.setItemLabelGenerator(new XYItemLabelGenerator("{2}", dateFormat, dateFormat));
                else
                    renderer.setItemLabelGenerator(
                            new XYItemLabelGenerator(dataLabelStyle, dateFormat, dateFormat));
            }
        } else {
            if (dataLabelStyle.equals("none")) {
                renderer.setItemLabelsVisible(false);
            } else {
                setXYItemLabelsData(renderer, seriesData);
                if (dataLabelStyle.equals("value")) {

                    renderer.setItemLabelGenerator(
                            new StandardXYItemLabelGenerator("{2}", numberFormat, numberFormat));

                } else if (dataLabelStyle.equals("rowlabel")) {

                    renderer.setItemLabelGenerator(
                            new StandardXYItemLabelGenerator("{0}", numberFormat, numberFormat));

                } else if (dataLabelStyle.equals("columnlabel")) {

                    if (series.get(0).getSeriesDataType() == cfCHARTSERIESData.XY_DATE_SERIES) {
                        renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator("{1}",
                                SimpleDateFormat.getInstance(), NumberFormat.getInstance()));
                    } else {
                        renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator("{1}",
                                NumberFormat.getInstance(), NumberFormat.getInstance()));
                    }

                } else if (dataLabelStyle.equals("pattern")) {

                    if (series.get(0).getSeriesDataType() == cfCHARTSERIESData.XY_DATE_SERIES) {
                        renderer.setItemLabelGenerator(new XYItemLabelGenerator("{1} {2} ({3} of {4})",
                                SimpleDateFormat.getInstance(), numberFormat));
                    } else {
                        renderer.setItemLabelGenerator(new XYItemLabelGenerator("{1} {2} ({3} of {4})",
                                NumberFormat.getInstance(), numberFormat));
                    }

                } else {
                    renderer.setItemLabelGenerator(
                            new XYItemLabelGenerator(dataLabelStyle, NumberFormat.getInstance(), numberFormat));
                }
            }
        }

        // Add the renderer to the plot.
        // NOTE: this must be done before the setPaintStyle() call so the
        // DrawingSupplier object
        // will be set up properly for the generation of default colors.
        plot.setRenderer(num, renderer);

        // Set the paint style for this series (series 0)
        if (seriesData.getType().equals("bar") || seriesData.getType().equals("horizontalbar")
                || seriesData.getType().equals("area"))
            setPaintStyle(seriesData.getPaintStyle(), renderer, 0, height);

        num++;
    }

    // If gridLines was specified then we need to calculate the yAxisUnits
    if ((gridLines != -1) && (valueAxis instanceof NumberAxis)) {
        // Calculate the yAxisUnits we need to use to create the number of
        // gridLines
        yAxisUnits = calculateYAxisUnits(gridLines, minMax);

        // Set the yAxisUnits
        ((NumberAxis) valueAxis).setTickUnit(new NumberTickUnit(yAxisUnits));
    }

    return plot;
}

From source file:com.jtstand.swing.StatsPanel.java

public JFreeChart getChartValues(Iterator<TestStepInstance> values) {
    if (values == null || !values.hasNext()) {
        return null;
    }//www . j  a  v  a2 s .co m

    XYSeriesCollection dataset = new XYSeriesCollection();
    int count = 0;
    TreeMap<String, XYSeries> map = new TreeMap<String, XYSeries>();
    while (values.hasNext()) {
        TestStepInstance step = values.next();
        Number num = getNumber(step);
        if (num != null) {
            String groupName = getGroupName(step);
            XYSeries pop = map.get(groupName);
            if (pop == null) {
                pop = new XYSeries(groupName);
                map.put(groupName, pop);
            }

            pop.add(++count, num.doubleValue());
        }

    }
    for (Iterator<XYSeries> it = map.values().iterator(); it.hasNext();) {
        dataset.addSeries(it.next());
    }

    //        NumberAxis xAxis = new NumberAxis("#");
    NumberAxis xAxis = new NumberAxis();
    xAxis.setAutoRangeIncludesZero(false);
    NumberAxis yAxis = new NumberAxis(getValueString());
    yAxis.setAutoRangeIncludesZero(false);
    XYLineAndShapeRenderer renderer6 = new XYLineAndShapeRenderer();
    XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer6);
    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setRangeCrosshairVisible(true);
    plot.setDomainCrosshairVisible(true);
    renderer6.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
    renderer6.setBaseSeriesVisibleInLegend(false);

    //        StandardXYItemLabelGenerator itemlabels=new StandardXYItemLabelGenerator();
    //        renderer.setBaseItemLabelGenerator(itemlabels);
    //        renderer.setBaseItemLabelsVisible(true);

    JFreeChart chart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, isGrouping());
    //chart.setTitle(title);
    placeLimitMarkers(plot, true);
    /* coloring */
    if (isCategorization()) {
        //            TreeMap<String, Color> cmap = new TreeMap<String, Color>();
        int i = 0;
        for (Iterator<String> it = catstats.keySet().iterator(); it.hasNext(); i++) {
            String groupName = it.next();
            Color c = ChartCategories.getColor(i);
            for (int j = 0; j < dataset.getSeriesCount(); j++) {
                XYSeries s = dataset.getSeries(j);
                if (s.getKey().equals(groupName)) {
                    renderer6.setSeriesPaint(j, c);
                }
            }
        }
    } else {
        renderer6.setSeriesPaint(0, ChartCategories.getColor(0));
    }
    chart.setTextAntiAlias(false);
    return chart;
}

From source file:com.jtstand.swing.StatsPanel.java

public JFreeChart getChartDistribution(boolean horizontal) {
    //        System.out.println("Min: " + minValue());
    //        System.out.println("Max: " + maxValue());
    XYIntervalSeriesCollection datasetDistribution = createIntervalXYDatasetDistribution(horizontal);
    XYSeriesCollection dataset2 = createXYDatasetGauss(horizontal);
    // create the chart...
    NumberAxis xAxis = new NumberAxis(getValueString());
    xAxis.setAutoRangeIncludesZero(false);
    //        NumberAxis yAxis = new NumberAxis("Distribution");
    NumberAxis yAxis = new NumberAxis();
    yAxis.setAutoRangeIncludesZero(true);
    //XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer = new MyBarRenderer();
    XYPlot plot = new XYPlot(datasetDistribution, xAxis, yAxis, renderer);
    plot.setOrientation(horizontal ? PlotOrientation.HORIZONTAL : PlotOrientation.VERTICAL);
    renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
    JFreeChart chart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, isGrouping());
    chart.setBackgroundPaint((Paint) UIManager.get("Panel.background"));
    //        plot.setBackgroundPaint(Color.white);
    plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
    StandardXYItemLabelGenerator itemlabels = new StandardXYItemLabelGenerator();
    renderer.setBaseItemLabelGenerator(itemlabels);
    renderer.setBaseItemLabelsVisible(true);
    plot.setDataset(1, dataset2);/*  w w  w.j a  v  a 2s.  c  om*/
    plot.mapDatasetToRangeAxis(1, 1);
    //        ValueAxis domainAxis = plot.getDomainAxis();
    //domainAxis.setCategoryLabelPositions(horizontal?CategoryLabelPositions.STANDARD:CategoryLabelPositions.UP_90);
    ValueAxis axis2 = new NumberAxis("Gaussian");
    plot.setRangeAxis(1, axis2);
    axis2.setVisible(false);
    final XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer();
    //renderer2.setShapesVisible(false);
    //renderer2.setSeriesVisibleInLegend(false);
    renderer2.setBaseSeriesVisibleInLegend(false);
    //renderer2.setToolTipGenerator(new StandardCategoryToolTipGenerator());
    plot.setRenderer(1, renderer2);
    renderer.setUseYInterval(true);
    renderer.setBaseSeriesVisibleInLegend(false);
    /* coloring */
    Color c;
    if (isMultipleCategorization()) {
        //            TreeMap<String, Color> cmap = new TreeMap<String, Color>();
        int i = 0;
        for (Iterator<String> it = catstats.keySet().iterator(); it.hasNext(); i++) {
            String groupName = it.next();
            c = ChartCategories.getColor(i);
            for (int j = 0; j < datasetDistribution.getSeriesCount(); j++) {
                XYIntervalSeries s = datasetDistribution.getSeries(j);
                if (s.getKey().equals(groupName)) {
                    GradientPaint gp = new GradientPaint(0.0f, 0.0f, c, 0.0f, 0.0f, c.darker().darker());
                    renderer.setSeriesPaint(j, gp);
                }
            }
            for (int j = 0; j < dataset2.getSeriesCount(); j++) {
                XYSeries s = dataset2.getSeries(j);
                if (s.getKey().equals(groupName)) {
                    renderer2.setSeriesPaint(j, c);
                    renderer2.setSeriesShapesVisible(j, false);
                    renderer2.setSeriesStroke(j, myStroke);
                }
            }
        }
        c = Color.black;
    } else {
        c = ChartCategories.getColor(0);
        GradientPaint gp = new GradientPaint(0.0f, 0.0f, c, 0.0f, 0.0f, c.darker().darker());
        renderer.setSeriesPaint(0, gp);
    }
    renderer2.setSeriesPaint(0, c);
    renderer2.setSeriesShapesVisible(0, false);
    renderer2.setSeriesStroke(0, myStroke);

    placeLimitMarkers(plot, false);
    //        renderer.setAutoPopulateSeriesOutlinePaint(true);
    //        renderer.setBaseOutlinePaint(Color.black);
    //        renderer.setSeriesOutlinePaint(0, Color.black, true);
    //        renderer.setDrawBarOutline(true);

    renderer.setHighlightedItem(0, 0);
    yAxis.setAutoRange(false);
    yAxis.setAutoRange(true);
    xAxis.setRange(leftValue(0), rightValue(numberOfCategories - 1));
    chart.setTextAntiAlias(false);
    return chart;
}

From source file:com.griddynamics.jagger.monitoring.reporting.SystemUnderTestPlotsGeneralProvider.java

public Map<String, List<MonitoringReporterData>> createTaskPlots() {
    log.info("BEGIN: Create general task plots");

    Map<String, List<MonitoringReporterData>> taskPlots = new LinkedHashMap<String, List<MonitoringReporterData>>();
    GeneralStatistics generalStatistics = getStatistics();

    Set<String> taskIds = generalStatistics.findTaskIds();
    Set<String> boxIdentifiers = generalStatistics.findBoxIdentifiers();
    Set<String> sutUrls = generalStatistics.findSutUrls();
    for (GroupKey groupName : plotGroups.getPlotGroups().keySet()) {
        log.info("    Create general task plots for group '{}'", groupName);

        if (showPlotsByGlobal) {
            log.info("        Create general global task plots");

            List<MonitoringReporterData> plots = new LinkedList<MonitoringReporterData>();
            XYSeriesCollection chartsCollection = new XYSeriesCollection();
            LinkedHashMap<String, IntervalMarker> markers = new LinkedHashMap<String, IntervalMarker>();
            for (MonitoringParameter parameterId : plotGroups.getPlotGroups().get(groupName)) {
                log.info("            Create general global task plots for parameter '{}'", parameterId);

                MonitoringParameterBean param = MonitoringParameterBean.copyOf(parameterId);
                if (generalStatistics.hasGlobalStatistics(param)) {
                    XYSeries values = new XYSeries(param.getDescription());
                    long timeShift = 0;
                    int taskNum = 0;
                    for (String taskId : taskIds) {
                        log.info("                Create general global task plots for task '{}'", taskId);

                        long maxTime = 0;
                        for (MonitoringStatistics monitoringStatistics : generalStatistics
                                .findGlobalStatistics(taskId, param)) {
                            long time = monitoringStatistics.getTime();
                            double t = timeShift + time;
                            values.add(t, monitoringStatistics.getAverageValue());

                            if (time > maxTime) {
                                maxTime = time;
                            }//from w  ww  .ja  v a  2 s  .c  o m

                            if (showNumbers) {
                                IntervalMarker marker = markers.get(taskId);
                                if (marker == null) {
                                    marker = new IntervalMarker(t, t);
                                    marker.setLabel(monitoringStatistics.getTaskData().getNumber().toString());
                                    marker.setAlpha((taskNum % 2 == 0) ? 0.2f : 0.4f);

                                    int mod = taskNum % 3;
                                    if (mod == 0) {
                                        marker.setLabelAnchor(RectangleAnchor.CENTER);
                                    } else if (mod == 1) {
                                        marker.setLabelAnchor(RectangleAnchor.TOP);
                                    } else if (mod == 2) {
                                        marker.setLabelAnchor(RectangleAnchor.BOTTOM);
                                    }

                                    marker.setLabelFont(
                                            marker.getLabelFont().deriveFont(10.0f).deriveFont(Font.BOLD));
                                    markers.put(taskId, marker);
                                } else {
                                    if (t < marker.getStartValue()) {
                                        marker.setStartValue(t);
                                    }
                                    if (t > marker.getEndValue()) {
                                        marker.setEndValue(t);
                                    }
                                }
                            }
                        }
                        timeShift += maxTime;
                        taskNum++;
                    }
                    if (values.isEmpty()) {
                        values.add(0, 0);
                    }
                    chartsCollection.addSeries(values);
                }
            }

            log.debug("group name \n{} \nparams {}]\n", groupName,
                    Lists.newArrayList(plotGroups.getPlotGroups().get(groupName)));

            Pair<String, XYSeriesCollection> pair = ChartHelper.adjustTime(chartsCollection, markers.values());

            chartsCollection = pair.getSecond();

            String name = groupName.getUpperName();

            if (chartsCollection.getSeriesCount() > 0) {
                JFreeChart chart = ChartHelper.createXYChart(null, chartsCollection,
                        "Time (" + pair.getFirst() + ")", groupName.getLeftName(), 0, 1,
                        ChartHelper.ColorTheme.LIGHT);

                XYPlot plot = (XYPlot) chart.getPlot();
                for (IntervalMarker marker : markers.values()) {
                    plot.addDomainMarker(marker);
                }

                MonitoringReporterData monitoringReporterData = new MonitoringReporterData();
                monitoringReporterData.setParameterName(name);
                monitoringReporterData.setTitle(name);
                monitoringReporterData.setPlot(new JCommonDrawableRenderer(chart));
                plots.add(monitoringReporterData);
            }

            if (!plots.isEmpty()) {
                taskPlots.put(name, plots);
            }
        }

        if (showPlotsByBox) {
            log.info("        Create general box task plots");

            for (String boxIdentifier : boxIdentifiers) {
                log.info("            Create general box task plots for box '{}'", boxIdentifier);

                List<MonitoringReporterData> plots = new LinkedList<MonitoringReporterData>();
                XYSeriesCollection chartsCollection = new XYSeriesCollection();
                LinkedHashMap<String, IntervalMarker> markers = new LinkedHashMap<String, IntervalMarker>();
                for (MonitoringParameter parameterId : plotGroups.getPlotGroups().get(groupName)) {
                    log.info("                Create general box task plots for parameter '{}'", parameterId);

                    MonitoringParameterBean param = MonitoringParameterBean.copyOf(parameterId);
                    if (generalStatistics.hasBoxStatistics(param, boxIdentifier)) {
                        XYSeries values = new XYSeries(param.getDescription());
                        long timeShift = 0;
                        int taskNum = 0;
                        for (String taskId : taskIds) {
                            log.info("                    Create general box task plots for task '{}'", taskId);

                            long maxTime = 0;
                            for (MonitoringStatistics monitoringStatistics : generalStatistics
                                    .findBoxStatistics(taskId, param, boxIdentifier)) {
                                long time = monitoringStatistics.getTime();
                                double t = timeShift + time;
                                values.add(t, monitoringStatistics.getAverageValue());

                                if (time > maxTime) {
                                    maxTime = time;
                                }

                                if (showNumbers) {
                                    IntervalMarker marker = markers.get(taskId);
                                    if (marker == null) {
                                        marker = new IntervalMarker(t, t);
                                        marker.setLabel(
                                                monitoringStatistics.getTaskData().getNumber().toString());
                                        marker.setAlpha((taskNum % 2 == 0) ? 0.2f : 0.4f);

                                        int mod = taskNum % 3;
                                        if (mod == 0) {
                                            marker.setLabelAnchor(RectangleAnchor.CENTER);
                                        } else if (mod == 1) {
                                            marker.setLabelAnchor(RectangleAnchor.TOP);
                                        } else if (mod == 2) {
                                            marker.setLabelAnchor(RectangleAnchor.BOTTOM);
                                        }

                                        marker.setLabelFont(
                                                marker.getLabelFont().deriveFont(10.0f).deriveFont(Font.BOLD));
                                        markers.put(taskId, marker);
                                    } else {
                                        if (t < marker.getStartValue()) {
                                            marker.setStartValue(t);
                                        }
                                        if (t > marker.getEndValue()) {
                                            marker.setEndValue(t);
                                        }
                                    }
                                }
                            }
                            timeShift += maxTime;
                            taskNum++;
                        }
                        if (values.isEmpty()) {
                            values.add(0, 0);
                        }
                        chartsCollection.addSeries(values);
                    }
                }

                log.debug("group name \n{} \nparams {}]\n", groupName,
                        Lists.newArrayList(plotGroups.getPlotGroups().get(groupName)));

                Pair<String, XYSeriesCollection> pair = ChartHelper.adjustTime(chartsCollection,
                        markers.values());

                chartsCollection = pair.getSecond();

                String name = groupName.getUpperName() + " on " + boxIdentifier;

                if (chartsCollection.getSeriesCount() > 0) {
                    JFreeChart chart = ChartHelper.createXYChart(null, chartsCollection,
                            "Time (" + pair.getFirst() + ")", groupName.getLeftName(), 0, 1,
                            ChartHelper.ColorTheme.LIGHT);

                    XYPlot plot = (XYPlot) chart.getPlot();
                    for (IntervalMarker marker : markers.values()) {
                        plot.addDomainMarker(marker);
                    }

                    MonitoringReporterData monitoringReporterData = new MonitoringReporterData();
                    monitoringReporterData.setParameterName(name);
                    monitoringReporterData.setTitle(name);
                    monitoringReporterData.setPlot(new JCommonDrawableRenderer(chart));
                    plots.add(monitoringReporterData);
                }

                if (!plots.isEmpty()) {
                    taskPlots.put(name, plots);
                }
            }
        }

        if (showPlotsBySuT) {
            log.info("        Create general sut task plots");

            for (String sutUrl : sutUrls) {
                log.info("            Create general sut task plots for sut '{}'", sutUrl);

                List<MonitoringReporterData> plots = new LinkedList<MonitoringReporterData>();
                XYSeriesCollection chartsCollection = new XYSeriesCollection();
                LinkedHashMap<String, IntervalMarker> markers = new LinkedHashMap<String, IntervalMarker>();
                for (MonitoringParameter parameterId : plotGroups.getPlotGroups().get(groupName)) {
                    log.info("                Create general sut task plots for parameter '{}'", parameterId);

                    MonitoringParameterBean param = MonitoringParameterBean.copyOf(parameterId);
                    if (generalStatistics.hasSutStatistics(param, sutUrl)) {
                        XYSeries values = new XYSeries(param.getDescription());
                        long timeShift = 0;
                        int taskNum = 0;
                        for (String taskId : taskIds) {
                            log.info("                    Create general sut task plots for task '{}'", taskId);

                            long maxTime = 0;
                            for (MonitoringStatistics monitoringStatistics : generalStatistics
                                    .findSutStatistics(taskId, param, sutUrl)) {
                                long time = monitoringStatistics.getTime();
                                double t = timeShift + time;
                                values.add(t, monitoringStatistics.getAverageValue());

                                if (time > maxTime) {
                                    maxTime = time;
                                }

                                if (showNumbers) {
                                    IntervalMarker marker = markers.get(taskId);
                                    if (marker == null) {
                                        marker = new IntervalMarker(t, t);
                                        marker.setLabel(
                                                monitoringStatistics.getTaskData().getNumber().toString());
                                        marker.setAlpha((taskNum % 2 == 0) ? 0.2f : 0.4f);

                                        int mod = taskNum % 3;
                                        if (mod == 0) {
                                            marker.setLabelAnchor(RectangleAnchor.CENTER);
                                        } else if (mod == 1) {
                                            marker.setLabelAnchor(RectangleAnchor.TOP);
                                        } else if (mod == 2) {
                                            marker.setLabelAnchor(RectangleAnchor.BOTTOM);
                                        }

                                        marker.setLabelFont(
                                                marker.getLabelFont().deriveFont(10.0f).deriveFont(Font.BOLD));
                                        markers.put(taskId, marker);
                                    } else {
                                        if (t < marker.getStartValue()) {
                                            marker.setStartValue(t);
                                        }
                                        if (t > marker.getEndValue()) {
                                            marker.setEndValue(t);
                                        }
                                    }
                                }
                            }
                            timeShift += maxTime;
                            taskNum++;
                        }
                        if (values.isEmpty()) {
                            values.add(0, 0);
                        }
                        chartsCollection.addSeries(values);
                    }
                }

                log.debug("group name \n{} \nparams {}]\n", groupName,
                        Lists.newArrayList(plotGroups.getPlotGroups().get(groupName)));

                Pair<String, XYSeriesCollection> pair = ChartHelper.adjustTime(chartsCollection,
                        markers.values());

                chartsCollection = pair.getSecond();

                String name = groupName.getUpperName() + " on " + sutUrl;

                if (chartsCollection.getSeriesCount() > 0) {
                    JFreeChart chart = ChartHelper.createXYChart(null, chartsCollection,
                            "Time (" + pair.getFirst() + ")", groupName.getLeftName(), 0, 1,
                            ChartHelper.ColorTheme.LIGHT);

                    XYPlot plot = (XYPlot) chart.getPlot();
                    for (IntervalMarker marker : markers.values()) {
                        plot.addDomainMarker(marker);
                    }

                    MonitoringReporterData monitoringReporterData = new MonitoringReporterData();
                    monitoringReporterData.setParameterName(name);
                    monitoringReporterData.setTitle(name);
                    monitoringReporterData.setPlot(new JCommonDrawableRenderer(chart));
                    plots.add(monitoringReporterData);
                }

                if (!plots.isEmpty()) {
                    taskPlots.put(name, plots);
                }
            }
        }
    }

    clearStatistics();

    log.info("END: Create general task plots");

    return taskPlots;
}

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;
        }//from w  w  w  . j  a  va 2  s  .  com

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

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

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

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

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

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

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

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

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

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

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

            allActionsAndEvents.add(entry);
        }
    }

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

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

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

            AEEntry entry = new AEEntry();

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

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

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

            allActionsAndEvents.add(entry);
        }
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        }

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

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