Example usage for org.jfree.chart.plot XYPlot setRangeGridlinesVisible

List of usage examples for org.jfree.chart.plot XYPlot setRangeGridlinesVisible

Introduction

In this page you can find the example usage for org.jfree.chart.plot XYPlot setRangeGridlinesVisible.

Prototype

public void setRangeGridlinesVisible(boolean visible) 

Source Link

Document

Sets the flag that controls whether or not the range axis grid lines are visible.

Usage

From source file:eu.hydrologis.jgrass.charting.datamodels.MultiXYTimeChartCreator.java

/**
 * Make a composite with the plot of the supplied chartdata. There are several HINT* variables
 * that can be set to tweak and configure the plot.
 * // w ww. ja  v a2 s  . co m
 * @param parentComposite
 * @param chartData
 */
public void makePlot(Composite parentComposite, NumericChartData chartData) {
    final int tabNums = chartData.getTabItemNumbers();

    if (tabNums == 0) {
        return;
    }

    Shell dummyShell = null;
    // try {
    // dummyShell = PlatformUI.getWorkbench().getDisplay().getActiveShell();
    // } catch (Exception e) {
    dummyShell = new Shell(Display.getCurrent(), SWT.None);
    // }
    /*
     * wrapping panel needed in the case of hide checks
     */
    TabFolder tabFolder = null;
    if (tabNums > 1) {
        tabFolder = new TabFolder(parentComposite, SWT.BORDER);
        tabFolder.setLayout(new GridLayout());
        tabFolder.setLayoutData(
                new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
    }

    for (int i = 0; i < tabNums; i++) {
        NumericChartDataItem chartItem = chartData.getChartDataItem(i);
        int chartNums = chartItem.chartSeriesData.size();
        /*
         * are there data to create the lower chart panel
         */
        List<LinkedHashMap<String, Integer>> series = new ArrayList<LinkedHashMap<String, Integer>>();
        List<XYPlot> plots = new ArrayList<XYPlot>();
        List<JFreeChart> charts = new ArrayList<JFreeChart>();

        for (int j = 0; j < chartNums; j++) {
            final LinkedHashMap<String, Integer> chartSeries = new LinkedHashMap<String, Integer>();
            XYPlot chartPlot = null;
            JGrassChart chart = null;
            double[][][] cLD = chartItem.chartSeriesData.get(j);

            if (M_HINT_CREATE_CHART[i][j]) {

                final String[] cT = chartItem.seriesNames.get(j);
                final String title = chartItem.chartTitles.get(j);
                final String xT = chartItem.chartXLabels.get(j);
                final String yT = chartItem.chartYLabels.get(j);

                if (M_HINT_CHART_TYPE[i][j] == XYLINECHART) {
                    chart = new JGrassXYLineChart(cT, cLD);
                } else if (M_HINT_CHART_TYPE[i][j] == XYBARCHART) {
                    chart = new JGrassXYBarChart(cT, cLD, HINT_barwidth);
                } else if (M_HINT_CHART_TYPE[i][j] == TIMEYLINECHART) {
                    chart = new JGrassXYTimeLineChart(cT, cLD, Minute.class);
                    ((JGrassXYTimeLineChart) chart).setTimeAxisFormat(TIMEFORMAT);
                } else if (M_HINT_CHART_TYPE[i][j] == TIMEYBARCHART) {
                    chart = new JGrassXYTimeBarChart(cT, cLD, Minute.class, HINT_barwidth);
                    ((JGrassXYTimeBarChart) chart).setTimeAxisFormat(TIMEFORMAT);
                } else if (M_HINT_CHART_TYPE[i][j] == XYPOINTCHART) {
                    chart = new JGrassXYLineChart(cT, cLD);
                    ((JGrassXYLineChart) chart).toggleLineShapesDisplay(false, true);
                } else if (M_HINT_CHART_TYPE[i][j] == TIMEXYPOINTCHART) {
                    chart = new JGrassXYTimeLineChart(cT, cLD, Minute.class);
                    ((JGrassXYTimeLineChart) chart).setTimeAxisFormat(TIMEFORMAT);
                    ((JGrassXYTimeLineChart) chart).toggleLineShapesDisplay(false, true);
                } else {
                    chart = new JGrassXYLineChart(cT, cLD);
                }

                final Composite p1Composite = new Composite(dummyShell, SWT.None);
                p1Composite.setLayout(new FillLayout());
                p1Composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
                chart.makeChartPanel(p1Composite, title, xT, yT, null, true, true, true, true);
                chartPlot = (XYPlot) chart.getPlot();
                XYItemRenderer renderer = chartPlot.getRenderer();

                chartPlot.setDomainGridlinesVisible(HINT_doDomainGridVisible);
                chartPlot.setRangeGridlinesVisible(HINT_doRangeGridVisible);

                if (HINT_doDisplayToolTips) {
                    renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
                }

                if (!M_HINT_CHARTORIENTATION_UP[i][j]) {
                    chartPlot.getRangeAxis().setInverted(true);
                }
                if (M_HINT_CHARTSERIESCOLOR != null) {
                    final XYItemRenderer rend = renderer;

                    for (int k = 0; k < cLD.length; k++) {
                        rend.setSeriesPaint(k, M_HINT_CHARTSERIESCOLOR[i][j][k]);
                    }
                }
                chart.toggleFilledShapeDisplay(HINT_doDisplayBaseShapes, HINT_doFillBaseShapes, true);

                for (int k = 0; k < cT.length; k++) {
                    chartSeries.put(cT[k], k);
                }
                series.add(chartSeries);
                chartPlot.setNoDataMessage("No data available");
                chartPlot.setNoDataMessagePaint(Color.red);
                plots.add(chartPlot);

                charts.add(chart.getChart(title, xT, yT, null, true, HINT_doDisplayToolTips, true));
                chartsList.add(chart);

                /*
                 * add annotations?
                 */
                if (chartItem.annotationsOnChart.size() > 0) {
                    LinkedHashMap<String, double[]> annotations = chartItem.annotationsOnChart.get(j);
                    if (annotations.size() > 0) {
                        Set<String> keys = annotations.keySet();
                        for (String key : keys) {
                            double[] c = annotations.get(key);
                            XYPointerAnnotation ann = new XYPointerAnnotation(key, c[0], c[1],
                                    HINT_AnnotationArrowAngle);
                            ann.setTextAnchor(HINT_AnnotationTextAncor);
                            ann.setPaint(HINT_AnnotationTextColor);
                            ann.setArrowPaint(HINT_AnnotationArrowColor);
                            // ann.setArrowLength(15);
                            renderer.addAnnotation(ann);

                            // Marker currentEnd = new ValueMarker(c[0]);
                            // currentEnd.setPaint(Color.red);
                            // currentEnd.setLabel("");
                            // currentEnd.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
                            // currentEnd.setLabelTextAnchor(TextAnchor.TOP_LEFT);
                            // chartPlot.addDomainMarker(currentEnd);

                            // Drawable cd = new LineDrawer(Color.red, new BasicStroke(1.0f));
                            // XYAnnotation bestBid = new XYDrawableAnnotation(c[0], c[1]/2.0,
                            // 0, c[1],
                            // cd);
                            // chartPlot.addAnnotation(bestBid);
                            // pointer.setFont(new Font("SansSerif", Font.PLAIN, 9));
                        }
                    }
                }
            }

        }

        JFreeChart theChart = null;

        if (plots.size() > 1) {

            ValueAxis domainAxis = null;
            if (M_HINT_CHART_TYPE[i][0] == ChartCreator.TIMEYBARCHART
                    || M_HINT_CHART_TYPE[i][0] == ChartCreator.TIMEYLINECHART) {

                domainAxis = (plots.get(0)).getDomainAxis();
            } else {
                domainAxis = new NumberAxis(chartItem.chartXLabels.get(0));
            }

            final CombinedDomainXYPlot plot = new CombinedDomainXYPlot(domainAxis);
            plot.setGap(10.0);
            // add the subplots...
            for (int k = 0; k < plots.size(); k++) {
                XYPlot tmpPlot = plots.get(k);

                if (HINT_labelInsets != null) {
                    tmpPlot.getRangeAxis().setLabelInsets(HINT_labelInsets);
                }

                plot.add(tmpPlot, k + 1);
            }
            plot.setOrientation(PlotOrientation.VERTICAL);

            theChart = new JFreeChart(chartItem.bigTitle, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
        } else if (plots.size() == 1) {
            theChart = new JFreeChart(chartItem.chartTitles.get(0), JFreeChart.DEFAULT_TITLE_FONT, plots.get(0),
                    true);
        } else {
            return;
        }

        /*
         * create the chart composite
         */
        Composite tmp;
        if (tabNums > 1 && tabFolder != null) {
            tmp = new Composite(tabFolder, SWT.None);
        } else {
            tmp = new Composite(parentComposite, SWT.None);
        }
        tmp.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
        tmp.setLayout(new GridLayout());
        final ChartComposite frame = new ChartComposite(tmp, SWT.None, theChart, 680, 420, 300, 200, 700, 500,
                false, true, // properties
                true, // save
                true, // print
                true, // zoom
                true // tooltips
        );

        // public static final boolean DEFAULT_BUFFER_USED = false;
        // public static final int DEFAULT_WIDTH = 680;
        // public static final int DEFAULT_HEIGHT = 420;
        // public static final int DEFAULT_MINIMUM_DRAW_WIDTH = 300;
        // public static final int DEFAULT_MINIMUM_DRAW_HEIGHT = 200;
        // public static final int DEFAULT_MAXIMUM_DRAW_WIDTH = 800;
        // public static final int DEFAULT_MAXIMUM_DRAW_HEIGHT = 600;
        // public static final int DEFAULT_ZOOM_TRIGGER_DISTANCE = 10;

        frame.setLayoutData(
                new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
        frame.setLayout(new FillLayout());
        frame.setDisplayToolTips(HINT_doDisplayToolTips);
        frame.setHorizontalAxisTrace(HINT_doHorizontalAxisTrace);
        frame.setVerticalAxisTrace(HINT_doVerticalAxisTrace);
        frame.setDomainZoomable(HINT_doDomainZoomable);
        frame.setRangeZoomable(HINT_doRangeZoomable);

        if (tabNums > 1 && tabFolder != null) {
            final TabItem item = new TabItem(tabFolder, SWT.NONE);
            item.setText(chartData.getChartDataItem(i).chartStringExtra);
            item.setControl(tmp);
        }

        /*
         * create the hide toggling part
         */
        for (int j = 0; j < plots.size(); j++) {

            if (M_HINT_CREATE_TOGGLEHIDESERIES[i][j]) {
                final LinkedHashMap<Button, Integer> allButtons = new LinkedHashMap<Button, Integer>();
                Group checksComposite = new Group(tmp, SWT.None);
                checksComposite.setText("");
                RowLayout rowLayout = new RowLayout();
                rowLayout.wrap = true;
                rowLayout.type = SWT.HORIZONTAL;
                checksComposite.setLayout(rowLayout);
                checksComposite
                        .setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));

                final XYItemRenderer renderer = plots.get(j).getRenderer();
                Set<String> lTitles = series.get(j).keySet();
                for (final String title : lTitles) {
                    final Button b = new Button(checksComposite, SWT.CHECK);
                    b.setText(title);
                    b.setSelection(true);
                    final int index = series.get(j).get(title);
                    b.addSelectionListener(new SelectionAdapter() {
                        public void widgetSelected(SelectionEvent e) {
                            boolean visible = renderer.getItemVisible(index, 0);
                            renderer.setSeriesVisible(index, new Boolean(!visible));
                        }
                    });
                    allButtons.put(b, index);
                }

                /*
                 * toggle all and none
                 */
                if (HINT_doToggleTuttiButton) {
                    Composite allchecksComposite = new Composite(tmp, SWT.None);
                    RowLayout allrowLayout = new RowLayout();
                    allrowLayout.wrap = true;
                    allrowLayout.type = SWT.HORIZONTAL;
                    allchecksComposite.setLayout(allrowLayout);
                    allchecksComposite
                            .setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));

                    final Button tuttiButton = new Button(allchecksComposite, SWT.BORDER | SWT.PUSH);
                    tuttiButton.setText("Tutti");
                    tuttiButton.addSelectionListener(new SelectionAdapter() {
                        public void widgetSelected(SelectionEvent e) {
                            Set<Button> set = allButtons.keySet();
                            for (Button button : set) {
                                button.setSelection(true);
                                int i = allButtons.get(button);
                                if (renderer != null) {
                                    renderer.setSeriesVisible(i, new Boolean(true));
                                }
                            }
                        }
                    });
                    final Button noneButton = new Button(allchecksComposite, SWT.BORDER | SWT.PUSH);
                    noneButton.setText("Nessuno");
                    noneButton.addSelectionListener(new SelectionAdapter() {
                        public void widgetSelected(SelectionEvent e) {
                            Set<Button> set = allButtons.keySet();
                            for (Button button : set) {
                                button.setSelection(false);
                                int i = allButtons.get(button);
                                if (renderer != null) {
                                    renderer.setSeriesVisible(i, new Boolean(false));
                                }
                            }
                        }
                    });
                }

            }

        }

    }
}

From source file:my.electrochem.ElectrochemUI.java

private ChartPanel createChartPanel() {
    //creates a line chart object
    //returns the chart panel
    String chartTitle = "i-E curve";
    String xAxisLabel = "E (V)";
    String yAxisLabel = "i (A)";

    dataset1 = createEmptyDataset();// w  w  w. j  a  va  2  s .  c  o  m

    JFreeChart chart = ChartFactory.createScatterPlot(chartTitle, xAxisLabel, yAxisLabel, dataset1);

    XYPlot plot = chart.getXYPlot();

    plot.setDomainCrosshairVisible(false);
    plot.setRangeCrosshairVisible(false);
    plot.setDomainCrosshairLockedOnData(false);
    plot.setRangeCrosshairLockedOnData(false);

    /*chart.addProgressListener(new ChartProgressListener() {
    @Override
    public void chartProgress(ChartProgressEvent cpe) {
        if (cpe.getType() == ChartProgressEvent.DRAWING_FINISHED) {
            //System.out.println("Click event!!");
            XYPlot xyPlot2 = cpe.getChart().getXYPlot();
            System.out.println("drawing finished");
            System.out.println("Xreal:"+xyPlot2.getDomainCrosshairValue()
                   +"Yreal:"+xyPlot2.getRangeCrosshairValue());
            if (click) {
                System.out.println("click true");
                if (x1 == -423.0) {
                    x1 = 0.0;
                    y1 = 0.0;
                            
                }
            
                if (x1 == 0.0 && y1 == 0.0) {
                    System.out.println("print 0,0");
                    click = true;
                    x1 = xyPlot2.getDomainCrosshairValue();
                    y1 = xyPlot2.getRangeCrosshairValue();
                    //xyPlot2.clearAnnotations();
                } else {
                    xyPlot2.clearAnnotations();
                    System.out.println("true-false");
                    click = false;
                    x1 = xyPlot2.getDomainCrosshairValue();
                    y1 = xyPlot2.getRangeCrosshairValue();
                }
                      
                             
            } else {
                System.out.println("click false");
               x2 = xyPlot2.getDomainCrosshairValue();
               y2 = xyPlot2.getRangeCrosshairValue();
               createLineAnn(xyPlot2, x1, y1, x2, y2);
               click = true;
           }
       }
       }
    });*/

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();

    // sets paint color for each series
    //renderer.setSeriesPaint(0, Color.RED);

    // sets thickness for series (using strokes)
    //renderer.setSeriesStroke(0, new BasicStroke(5.0f));
    renderer.setBaseLinesVisible(true);
    //renderer.setSeriesLinesVisible(0, true);

    //renderer.setBaseShapesFilled(true);
    renderer.setBaseShapesVisible(false);
    //srenderer.setDrawSeriesLineAsPath(false);

    plot.setOutlinePaint(Color.BLUE);
    plot.setOutlineStroke(new BasicStroke(2.0f));
    plot.setBackgroundPaint(Color.DARK_GRAY);

    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.BLACK);

    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.BLACK);

    plot.setRenderer(renderer);

    return new ChartPanel(chart);
}

From source file:com.afunms.system.manage.equipManager.java

/**
 * Creates a sample chart.//from   w  w w  . j  a v a  2s. c  om
 * 
 * @return a sample chart.
 */
private JFreeChart createChart() {
    final XYDataset direction = createDirectionDataset(600);
    final JFreeChart chart = ChartFactory.createTimeSeriesChart("", "", "", direction,
            true, true, false);

    final XYPlot plot = chart.getXYPlot();
    plot.getDomainAxis().setLowerMargin(0.0);
    plot.getDomainAxis().setUpperMargin(0.0);
    plot.setRangeCrosshairVisible(true);
    plot.setDomainCrosshairVisible(true);
    plot.setBackgroundPaint(Color.WHITE);
    plot.setForegroundAlpha(0.8f);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.darkGray);
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(new Color(139, 69, 19));
    XYLineAndShapeRenderer render0 = (XYLineAndShapeRenderer) plot.getRenderer(0);
    render0.setSeriesPaint(0, Color.BLUE);

    XYAreaRenderer xyarearenderer = new XYAreaRenderer();
    xyarearenderer.setSeriesPaint(1, Color.GREEN); // 
    xyarearenderer.setSeriesFillPaint(1, Color.GREEN);
    xyarearenderer.setPaint(Color.GREEN);

    // configure the range axis to display directions...
    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setAutoRangeIncludesZero(false);
    final TickUnits units = new TickUnits();
    units.add(new NumberTickUnit(180.0, new CompassFormat()));
    units.add(new NumberTickUnit(90.0, new CompassFormat()));
    units.add(new NumberTickUnit(45.0, new CompassFormat()));
    units.add(new NumberTickUnit(22.5, new CompassFormat()));
    rangeAxis.setStandardTickUnits(units);

    // add the wind force with a secondary dataset/renderer/axis
    plot.setRangeAxis(rangeAxis);
    final XYItemRenderer renderer2 = new XYAreaRenderer();
    final ValueAxis axis2 = new NumberAxis("");
    axis2.setRange(0.0, 12.0);
    xyarearenderer.setSeriesPaint(1, new Color(0, 204, 0)); // 
    xyarearenderer.setSeriesFillPaint(1, Color.GREEN);
    xyarearenderer.setPaint(Color.GREEN);
    plot.setDataset(1, createForceDataset(600));
    plot.setRenderer(1, xyarearenderer);
    plot.setRangeAxis(1, axis2);
    plot.mapDatasetToRangeAxis(1, 1);

    return chart;
}

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

private JFreeChart renderXYChart(cfSession _Session, cfCHARTInternalData chartData, String tipStyle,
        String drillDownUrl, String seriesPlacement, int height) throws cfmRunTimeException {
    List<cfCHARTSERIESData> series = chartData.getSeries();

    if (seriesPlacement.equals("stacked") || seriesPlacement.equals("percent"))
        throw newRunTimeException(
                "A chart with an xAxisType of 'scale' cannot be displayed with a seriesPlacement of '"
                        + seriesPlacement + "'");

    // Retrieve the attributes of the chart
    String backgroundColorStr = getDynamic(_Session, "BACKGROUNDCOLOR").toString();
    Color backgroundColor = convertStringToColor(backgroundColorStr);

    String dataBackgroundColorStr = getDynamic(_Session, "DATABACKGROUNDCOLOR").toString();
    Color dataBackgroundColor = convertStringToColor(dataBackgroundColorStr);

    String foregroundColorStr = getDynamic(_Session, "FOREGROUNDCOLOR").toString();
    Color foregroundColor = convertStringToColor(foregroundColorStr);

    String labelFormat = getDynamic(_Session, "LABELFORMAT").toString().toLowerCase();
    if (!labelFormat.equals("number") && !labelFormat.equals("currency") && !labelFormat.equals("percent")
            && !labelFormat.equals("date"))
        throw newRunTimeException("The labelFormat value '" + labelFormat + "' is not supported");

    String xAxisTitle = null;//from  w w w .  j ava 2  s. co m
    if (containsAttribute("XAXISTITLE"))
        xAxisTitle = getDynamic(_Session, "XAXISTITLE").toString();

    String yAxisTitle = null;
    if (containsAttribute("YAXISTITLE"))
        yAxisTitle = getDynamic(_Session, "YAXISTITLE").toString();

    String title = null;
    if (containsAttribute("TITLE"))
        title = getDynamic(_Session, "TITLE").toString();

    Font font = getFont(_Session);

    int yAxisUnits = 0;
    if (containsAttribute("YAXISUNITS")) {
        if (containsAttribute("GRIDLINES"))
            throw newRunTimeException("You cannot specify both yAxisUnits and gridLines");
        yAxisUnits = getDynamic(_Session, "YAXISUNITS").getInt();
        if (yAxisUnits < 0)
            throw newRunTimeException("You must specify a positive value for yAxisUnits");
    }
    int gridLines = -1;
    if (containsAttribute("GRIDLINES")) {
        gridLines = getDynamic(_Session, "GRIDLINES").getInt();
        if (gridLines < 2)
            throw newRunTimeException("You must specify a value greater than 1 for gridLines");
    }
    int markerSize = getDynamic(_Session, "MARKERSIZE").getInt();
    int xOffset = getDynamic(_Session, "XOFFSET").getInt();
    if (xOffset < 0)
        throw newRunTimeException("You must specify a positive value for xOffset");

    double xUpperMargin = getDynamic(_Session, "XAXISUPPERMARGIN").getDouble();
    if (xUpperMargin < 0)
        throw newRunTimeException("You must specify a positive value for xAxisUpperMargin");

    int yOffset = getDynamic(_Session, "YOFFSET").getInt();
    if (yOffset < 0)
        throw newRunTimeException("You must specify a positive value for yOffset");

    double yUpperMargin = getDynamic(_Session, "YAXISUPPERMARGIN").getDouble();
    if (yUpperMargin < 0)
        throw newRunTimeException("You must specify a positive value for yAxisUpperMargin");

    boolean bShow3D = getDynamic(_Session, "SHOW3D").getBoolean();
    if (bShow3D)
        throw newRunTimeException("A chart with an xAxisType of 'scale' cannot be displayed in 3D");
    boolean bShowMarkers = getDynamic(_Session, "SHOWMARKERS").getBoolean();
    boolean bShowBorder = getDynamic(_Session, "SHOWBORDER").getBoolean();
    boolean bShowXGridlines = getDynamic(_Session, "SHOWXGRIDLINES").getBoolean();
    boolean bShowYGridlines = getDynamic(_Session, "SHOWYGRIDLINES").getBoolean();

    boolean bShowLegend = false; // default to false for category charts
    if (containsAttribute("SHOWLEGEND"))
        bShowLegend = getDynamic(_Session, "SHOWLEGEND").getBoolean();

    int scaleFrom = Integer.MIN_VALUE;
    if (containsAttribute("SCALEFROM"))
        scaleFrom = getDynamic(_Session, "SCALEFROM").getInt();

    int scaleTo = Integer.MIN_VALUE;
    if (containsAttribute("SCALETO"))
        scaleTo = getDynamic(_Session, "SCALETO").getInt();

    // Get the plot for the chart and configure it
    XYPlot plot = getXYPlot(series, xAxisTitle, yAxisTitle, labelFormat, bShowMarkers, markerSize, bShow3D,
            tipStyle, drillDownUrl, xOffset, yOffset, yAxisUnits, seriesPlacement, height, gridLines);

    // Render the datasets/series in the order they appear in the cfchart tag
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    plot.getDomainAxis().setLabelFont(font);
    plot.getDomainAxis().setTickLabelFont(font);
    plot.getDomainAxis().setAxisLinePaint(foregroundColor);
    plot.getDomainAxis().setLabelPaint(foregroundColor);
    plot.getDomainAxis().setTickLabelPaint(foregroundColor);
    plot.getDomainAxis().setUpperMargin(xUpperMargin);
    plot.setDomainGridlinesVisible(bShowXGridlines);
    plot.setRangeGridlinesVisible(bShowYGridlines);
    plot.getRangeAxis().setLabelFont(font);
    plot.getRangeAxis().setTickLabelFont(font);
    plot.getRangeAxis().setAxisLinePaint(foregroundColor);
    plot.getRangeAxis().setLabelPaint(foregroundColor);
    plot.getRangeAxis().setTickLabelPaint(foregroundColor);
    plot.getRangeAxis().setUpperMargin(yUpperMargin);
    if (scaleFrom != Integer.MIN_VALUE)
        plot.getRangeAxis().setLowerBound(scaleFrom);
    if (scaleTo != Integer.MIN_VALUE)
        plot.getRangeAxis().setUpperBound(scaleTo);
    plot.setBackgroundPaint(dataBackgroundColor);
    plot.setOutlinePaint(foregroundColor);
    setBackgroundImage(_Session, plot, chartData.getImageData());

    // Add Range Markers
    List<cfCHARTRANGEMARKERData> rangeMarkers = chartData.getRangeMarkers();
    for (int i = 0; i < rangeMarkers.size(); i++)
        addRangeMarker(plot, rangeMarkers.get(i));

    // Add Domain Markers
    List<cfCHARTDOMAINMARKERData> domainMarkers = chartData.getDomainMarkers();
    for (int i = 0; i < domainMarkers.size(); i++)
        addDomainMarker(plot, domainMarkers.get(i));

    // Get the chart and configure it
    JFreeChart chart = new JFreeChart(null, null, plot, false);
    chart.setBorderVisible(bShowBorder);
    chart.setBackgroundPaint(backgroundColor);
    setTitle(chart, title, font, foregroundColor, chartData.getTitles());
    setLegend(chart, bShowLegend, font, foregroundColor, backgroundColor, chartData.getLegendData());

    return chart;
}

From source file:de.dmarcini.submatix.pclogger.gui.spx42LogGraphPanel.java

/**
 * Zeichne die eigentliche Grafik Project: SubmatixBTForPC Package: de.dmarcini.submatix.pclogger.gui
 * //  ww w . j ava 2 s  .c  om
 * @author Dirk Marciniak (dirk_marciniak@arcor.de) Stand: 03.07.2012
 * @param dbId
 *          dbid in Tabelle D_TABLE_DIVEDETAIL
 * @param device
 */
private void makeGraphForLog(int dbId, String device) {
    Vector<Integer[]> diveList;
    Vector<String> diluents;
    int[] headData;
    XYPlot thePlot;
    JFreeChart logChart;
    int min, sec;
    // das alte Zeug entsorgen
    releaseGraph();
    //
    // Daten eines TG lesen
    //
    lg.debug("read dive log from DB...");
    diveList = databaseUtil.getDiveDataFromIdLog(dbId);
    if (diveList == null || diveList.isEmpty()) {
        return;
    }
    //
    // verwendete Diluents finden
    //
    diluents = getDiluentNamesFromDive(diveList);
    // Anzeigen
    String diluentString = StringUtils.join(diluents, ", ");
    diluentLabel.setText(
            String.format(LangStrings.getString("spx42LogGraphPanel.diluentLabel.text"), diluentString));
    lg.debug(diluents);
    //
    // Labels fr Tachgangseckdaten fllen
    //
    headData = databaseUtil.getHeadDiveDataFromIdLog(dbId);
    notesLabel.setText(databaseUtil.getNotesForIdLog(dbId));
    showingUnitSystem = SpxPcloggerProgramConfig.unitsProperty;
    savedUnitSystem = headData[6];
    // jetzt die Strings fr Masseinheiten holen
    String[] labels = getUnitsLabel(showingUnitSystem, savedUnitSystem);
    depthUnitName = labels[0];
    tempUnitName = labels[1];
    pressureUnitName = labels[2];
    //
    // entscheide ob etwas umgerechnet werden sollte
    //
    if (showingUnitSystem == savedUnitSystem || showingUnitSystem == ProjectConst.UNITS_DEFAULT) {
        // nein, alles schick
        maxDepthValueLabel.setText(String.format(maxDepthLabelString, (headData[3] / 10.0), depthUnitName));
        coldestTempValueLabel.setText(String.format(coldestLabelString, (headData[2] / 10.0), tempUnitName));
    } else {
        // umrechnen!
        if (showingUnitSystem == ProjectConst.UNITS_IMPERIAL) {
            // metrisch-> imperial konvertieren
            // 1 foot == 30,48 cm == 0.3048 Meter
            maxDepthValueLabel
                    .setText(String.format(maxDepthLabelString, (headData[3] / 10.0) / 0.3048, depthUnitName));
            // t F = 5?9 (t  32) C
            coldestTempValueLabel.setText(
                    String.format(coldestLabelString, (5.0 / 9.0) * ((headData[2] / 10.0) - 32), tempUnitName));
        } else {
            maxDepthValueLabel
                    .setText(String.format(maxDepthLabelString, (headData[3] / 10.0) * 0.3048, depthUnitName));
            // t C = (9?5 t + 32) F
            coldestTempValueLabel.setText(
                    String.format(coldestLabelString, ((9.0 / 5.0) * (headData[2] / 10.0)) + 32, tempUnitName));
        }
    }
    min = headData[5] / 60;
    sec = headData[5] % 60;
    diveLenValueLabel.setText(String.format(diveLenLabelString, min, sec, "min"));
    //
    // einen Plot machen (Grundlage des Diagramms)
    //
    lg.debug("create graph...");
    thePlot = new XYPlot();
    //
    // Eigenschaften definieren
    //
    thePlot.setBackgroundPaint(Color.lightGray);
    thePlot.setDomainGridlinesVisible(true);
    thePlot.setDomainGridlinePaint(Color.white);
    thePlot.setRangeGridlinesVisible(true);
    thePlot.setRangeGridlinePaint(Color.white);
    thePlot.setDomainPannable(true);
    thePlot.setRangePannable(false);
    //
    // ein Chart zur Anzeige in einem Panel erzeugen
    //
    logChart = new JFreeChart(LangStrings.getString("spx42LogGraphPanel.graph.chartTitle"), thePlot);
    logChart.setAntiAlias(true);
    logChart.addSubtitle(new TextTitle(LangStrings.getString("spx42LogGraphPanel.graph.chartSubTitle")));
    // ein Thema zufgen, damit ich eigene Farben einbauen kann
    ChartUtilities.applyCurrentTheme(logChart);
    //
    // ein Diagramm-Panel erzeugen
    //
    chartPanel = new ChartPanel(logChart);
    chartPanel.setMouseZoomable(true);
    chartPanel.setAutoscrolls(true);
    chartPanel.setMouseWheelEnabled(true);
    chartPanel.setRangeZoomable(false);
    chartPanel.setDisplayToolTips(false);
    chartPanel.setZoomTriggerDistance(10);
    add(chartPanel, BorderLayout.CENTER);
    //
    // Datumsachse umformatieren
    //
    final NumberAxis axis = new NumberAxis(LangStrings.getString("spx42LogGraphPanel.graph.dateAxisTitle"));
    MinuteFormatter formatter = new MinuteFormatter(
            LangStrings.getString("spx42LogGraphPanel.graph.dateAxisUnit"));
    axis.setNumberFormatOverride(formatter);
    thePlot.setDomainAxis(axis);
    //
    // Temperatur einfgen
    //
    if (SpxPcloggerProgramConfig.showTemperature) {
        makeTemperatureGraph(diveList, thePlot, labels);
    }
    //
    // Partialdruck einfgen
    // die Achse erst mal machen
    final NumberAxis ppo2Axis = new NumberAxis(
            LangStrings.getString("spx42LogGraphPanel.graph.ppo2AxisTitle") + " " + pressureUnitName);
    final NumberAxis percentAxis = new NumberAxis(LangStrings.getString("spx42LogGraphPanel.graph.inertgas"));
    //
    // wenn eine der Achsen dargesstellt werden muss, dann sollte die Achse auch in der Grafil da sein
    //
    if (SpxPcloggerProgramConfig.showPpo01 || SpxPcloggerProgramConfig.showPpo02
            || SpxPcloggerProgramConfig.showPpo03 || SpxPcloggerProgramConfig.showPpoResult
            || SpxPcloggerProgramConfig.showSetpoint) {
        ppo2Axis.setAutoRangeIncludesZero(false);
        ppo2Axis.setAutoRange(false);
        //
        // wie skaliere ich die Achse?
        //
        if (showingUnitSystem == ProjectConst.UNITS_DEFAULT) {
            // so wie gespeichert
            if (savedUnitSystem == ProjectConst.UNITS_METRIC) {
                ppo2Axis.setRange(0.0, 3.5);
            } else {
                ppo2Axis.setRange(0.0, (3.5 * 14.504));
            }
        } else if (showingUnitSystem == ProjectConst.UNITS_METRIC) {
            ppo2Axis.setRange(0.0, 3.5);
        } else {
            ppo2Axis.setRange(0.0, (3.5 * 14.504));
        }
        ppo2Axis.setLabelPaint(new Color(ProjectConst.GRAPH_PPO2ALL_ACOLOR));
        ppo2Axis.setTickLabelPaint(new Color(ProjectConst.GRAPH_PPO2ALL_ACOLOR));
        thePlot.setRangeAxis(GRAPH_PPO2ALL, ppo2Axis);
    }
    if (SpxPcloggerProgramConfig.showHe || SpxPcloggerProgramConfig.showN2) {
        percentAxis.setAutoRangeIncludesZero(false);
        percentAxis.setAutoRange(false);
        percentAxis.setRange(0.0, 100.0);
        percentAxis.setLabelPaint(new Color(ProjectConst.GRAPH_INNERTGAS_ACOLOR));
        percentAxis.setTickLabelPaint(new Color(ProjectConst.GRAPH_INNERTGAS_ACOLOR));
        thePlot.setRangeAxis(GRAPH_HE, percentAxis);
    }
    //
    // Partialdrcke der einzelnen Sensoren einfgen
    //
    // Sensor 01 anzeigen
    if (SpxPcloggerProgramConfig.showPpo01) {
        makePpoGraph(diveList, thePlot, 1);
    }
    // Sensor 02 anzeigen
    if (SpxPcloggerProgramConfig.showPpo02) {
        makePpoGraph(diveList, thePlot, 2);
    }
    // Sensor 03 anzeigen
    if (SpxPcloggerProgramConfig.showPpo03) {
        makePpoGraph(diveList, thePlot, 3);
    }
    // Resultierenden PPO anzeigen
    if (SpxPcloggerProgramConfig.showPpoResult) {
        makePpoGraph(diveList, thePlot, 0);
        // makePpoResultGraph( diveList, thePlot );
    }
    if (SpxPcloggerProgramConfig.showSetpoint) {
        makeSetpointGraph(diveList, thePlot);
    }
    //
    // Helium und Stickstoffanteil im Gas?
    //
    if (SpxPcloggerProgramConfig.showHe) {
        makeInnertGasGraph(diveList, thePlot, "he");
    }
    if (SpxPcloggerProgramConfig.showN2) {
        makeInnertGasGraph(diveList, thePlot, "n2");
    }
    //
    // die Nullzeit auf Wunsch
    //
    if (SpxPcloggerProgramConfig.showNulltime) {
        makeNulltimeGraph(diveList, thePlot);
    }
    //
    // die Tiefe einfgen
    //
    makeDepthGraph(diveList, thePlot);
    //
    showingDbIdForDiveWasShowing = dbId;
    lg.debug("create graph...OK");
}

From source file:probe.com.view.body.quantdatasetsoverview.quantproteinstabsheet.studies.ProteinStudyComparisonScatterPlotLayout.java

/**
 * Creates a sample jFreeChart./*ww w. j  a  va 2 s.  c o  m*/
 *
 * @param dataset the dataset.
 *
 * @return The jFreeChart.
 */
private void generateScatterplotchart(DiseaseGroupsComparisonsProteinLayout cp, int w, int h) {

    final XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries downSer = new XYSeries(0);
    XYSeries stableSer = new XYSeries(1);
    XYSeries upSer = new XYSeries(2);

    XYSeries novalueProvidedSer = new XYSeries(3);

    XYSeries downSerII = new XYSeries(4);
    XYSeries stableSerII = new XYSeries(5);
    XYSeries upSerII = new XYSeries(6);
    XYSeries novalueProvidedSerII = new XYSeries(7);

    //        XYSeries plusSeries = new XYSeries(6);
    double downCounter = 1;
    double stableCounter = 3;
    double upCounter = 5;
    double novalueProvidedCounter = 3;

    patientGroupsNumToDsIdMap.clear();

    final Map<Integer, int[]> paTGrNumbtrendMap = new HashMap<Integer, int[]>();
    double maxPatNumber = -1.0;
    for (String protTrend : cp.getPatientsNumToTrindMap().keySet()) {
        List<Integer> patNums = cp.getPatientsNumToTrindMap().get(protTrend);
        int coun = 0;
        for (int i : patNums) {
            if (i > maxPatNumber) {
                maxPatNumber = i;
            }
            if (!patientGroupsNumToDsIdMap.containsKey(i)) {
                ComparisonDetailsBean pGr = new ComparisonDetailsBean();
                patientGroupsNumToDsIdMap.put(i, pGr);

            }
            if (!paTGrNumbtrendMap.containsKey(i)) {
                int[] values = new int[4];
                paTGrNumbtrendMap.put(i, values);
            }

            int[] values = paTGrNumbtrendMap.get(i);
            ComparisonDetailsBean pGr = patientGroupsNumToDsIdMap.get(i);
            if (protTrend.equalsIgnoreCase("noValueProvided")) {
                values[3] = values[3] + 1;
                pGr.addNovalueProvided(cp.getDSID(3, coun));

            } else if (protTrend.equalsIgnoreCase("up")) {
                values[2] = values[2] + 1;

                pGr.addUpRegulated(cp.getDSID(0, coun));

            } else if (protTrend.equalsIgnoreCase("down")) {
                values[0] = values[0] + 1;
                pGr.addDownRegulated(cp.getDSID(2, coun));
            } else {
                values[1] = values[1] + 1;
                pGr.addNotRegulated(cp.getDSID(1, coun));
            }
            paTGrNumbtrendMap.put(i, values);
            patientGroupsNumToDsIdMap.put(i, pGr);
            coun++;
        }

    }

    for (int i : paTGrNumbtrendMap.keySet()) {
        int[] values = paTGrNumbtrendMap.get(i);
        if ((values[2] > 1)) {
            upSer.add(upCounter, i);
            upSerII.add(upCounter, i);
        } else if ((values[2] == 1)) {
            upSer.add(upCounter, i);
        }
        if ((values[1] == 1)) {
            stableSer.add(stableCounter, i);
        } else if ((values[1] > 1)) {
            stableSer.add(stableCounter, i);
            stableSerII.add(stableCounter, i);
        }

        if ((values[0] > 1)) {
            downSer.add(downCounter, i);
            downSerII.add(downCounter, i);
        } else if ((values[0] == 1)) {
            downSer.add(downCounter, i);
        }
        if ((values[3] == 1)) {
            novalueProvidedSer.add(novalueProvidedCounter, i);
        } else if ((values[3] > 1)) {
            novalueProvidedSer.add(stableCounter, i);
            novalueProvidedSerII.add(stableCounter, i);
        }

    }

    dataset.addSeries(downSer);
    dataset.addSeries(stableSer);
    dataset.addSeries(upSer);
    dataset.addSeries(novalueProvidedSer);
    dataset.addSeries(downSerII);
    dataset.addSeries(stableSerII);
    dataset.addSeries(upSerII);
    dataset.addSeries(novalueProvidedSerII);
    //        if((downSerII.getItemCount()+stableSerII.getItemCount()+upSerII.getItemCount()+downSer.getItemCount()+stableSer.getItemCount()+upSer.getItemCount())==0)
    //            return;
    //        dataset.addSeries(plusSeries);
    final String[] labels = new String[] { " ", ("Decreased (" + cp.getSignificantDown() + ")"), " ",
            ("Equal (" + cp.getStable() + ")"), " ", ("Increased (" + cp.getSignificantUp() + ")"), "" };
    final Color[] labelsColor = new Color[] { Color.LIGHT_GRAY, new Color(80, 183, 71), Color.LIGHT_GRAY,
            new Color(1, 141, 244), Color.LIGHT_GRAY, Color.RED, Color.LIGHT_GRAY };
    final SymbolAxis domainAxis = new SymbolAxis("X", labels) {

        @Override
        protected void drawGridBandsVertical(Graphics2D g2, Rectangle2D drawArea, Rectangle2D plotArea,
                boolean firstGridBandIsDark, List ticks) {
            List udatedTicksList = new ArrayList();

            for (Object tick : ticks) {
                if (tick.toString().equalsIgnoreCase(labels[custTrend + 1])) {
                    udatedTicksList.add(tick);
                }
            }
            //                System.out.println("at ticks is "+ticks);
            //                 System.out.println("at udatedTicksList is "+udatedTicksList);
            //                int factor = (int) ((plotArea.getHeight() / 5) * 0.25);
            //
            //                Rectangle2D up = new Rectangle((int) drawArea.getX(), (int) drawArea.getY() - factor, (int) drawArea.getWidth(), (int) drawArea.getHeight());
            //                Rectangle2D pa = new Rectangle((int) plotArea.getX(), (int) plotArea.getY() - factor, (int) plotArea.getWidth(), (int) plotArea.getHeight());

            super.drawGridBandsVertical(g2, drawArea, plotArea, firstGridBandIsDark, udatedTicksList); //To change body of generated methods, choose Tools | Templates.
        }

        int x = 0;

        @Override
        public Paint getTickLabelPaint() {
            if (x >= labels.length) {
                x = 0;
            }
            return labelsColor[x++];
        }

    };
    domainAxis.setAutoRangeIncludesZero(false);
    Font f = new Font("Verdana", Font.PLAIN, 11);
    domainAxis.setTickLabelFont(f);
    domainAxis.setAutoRange(false);
    domainAxis.setLabel(null);

    //        domainAxis.setGridBandsVisible(false);
    String xTile = "#Patients";

    JFreeChart jFreeChart = ChartFactory.createScatterPlot(null, null, // domain axis label
            null, // range axis label
            dataset, // data
            PlotOrientation.HORIZONTAL, // orientation
            false, // include legend
            false, // tooltips?
            false // URLs?
    );
    XYPlot plot1 = (XYPlot) jFreeChart.getPlot();
    XYPlot xyplot = new XYPlot(dataset, plot1.getDomainAxis(), plot1.getRangeAxis(), plot1.getRenderer()) {

        @Override
        public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea, List ticks) {

            if (custTrend == -1) {
                super.drawDomainTickBands(g2, dataArea, ticks);
                return;

            }
            List udatedTicksList = new ArrayList();
            for (Object tick : ticks) {
                if (tick.toString().equalsIgnoreCase(labels[custTrend + 1])) {
                    udatedTicksList.add(tick);
                }
            }
            Rectangle2D up;
            int factor = (int) ((dataArea.getHeight() / 5) * 0.5);
            if (custTrend == 4) {
                up = new Rectangle((int) dataArea.getX(), (int) dataArea.getY() + factor,
                        (int) dataArea.getWidth(), (int) dataArea.getHeight());

            } else if (custTrend == 2) {
                up = new Rectangle((int) dataArea.getX(), (int) dataArea.getY() - factor,
                        (int) dataArea.getWidth(), (int) dataArea.getHeight());

            } else {
                up = new Rectangle((int) dataArea.getX(), (int) dataArea.getY() - factor,
                        (int) dataArea.getWidth(), (int) dataArea.getHeight());
            }

            super.drawDomainTickBands(g2, up, udatedTicksList); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea, List ticks) {
            super.drawDomainGridlines(g2, dataArea, ticks); //To change body of generated methods, choose Tools | Templates.
        }

        private int x = 0;

        @Override
        public Paint getDomainGridlinePaint() {
            if (x >= labels.length) {
                x = 0;
            }
            if (x == 1 || x == 3 || x == 5) {
                x++;
                return Color.WHITE;
            } else {
                x++;
                return super.getDomainGridlinePaint(); //To change body of generated methods, choose Tools | Templates.
            }
        }
    };
    if (custTrend != -1) {
        domainAxis.setGridBandsVisible(true);
        if (custTrend == 4) {
            domainAxis.setGridBandPaint(Color.decode("#ffe5e5"));
            xyplot.setDomainTickBandPaint(Color.decode("#ffe5e5"));
            domainAxis.setGridBandAlternatePaint(Color.decode("#ffe5e5"));
        } else if (custTrend == 0) {
            domainAxis.setGridBandPaint(Color.decode("#e5ffe5"));
            xyplot.setDomainTickBandPaint(Color.white);
        } else if (custTrend == 2) {
            domainAxis.setGridBandPaint(Color.decode("#e6f4ff"));
            xyplot.setDomainTickBandPaint(Color.white);
        }

    } else {
        domainAxis.setGridBandsVisible(false);
    }
    xyplot.setOrientation(PlotOrientation.HORIZONTAL);
    JFreeChart tempScatterPlot = new JFreeChart(xyplot);
    tempScatterPlot.setBackgroundPaint(Color.WHITE);
    tempScatterPlot.getLegend().setVisible(false);
    Color c = new Color(242, 242, 242);
    xyplot.setDomainAxis(domainAxis);
    xyplot.setDomainGridlinePaint(Color.GRAY);
    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.GRAY);
    xyplot.setOutlinePaint(Color.GRAY);
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyplot.getRenderer();
    ValueAxis va = xyplot.getDomainAxis();
    va.setAutoRange(false);
    va.setMinorTickCount(0);
    va.setVisible(true);
    maxPatNumber = Math.ceil(maxPatNumber / 100.0) * 100;
    xyplot.getRangeAxis().setRange(0, maxPatNumber);
    NumberAxis rangeAxis = (NumberAxis) xyplot.getRangeAxis();
    rangeAxis.setTickUnit(new NumberTickUnit(10));
    rangeAxis.setLabel(xTile);
    rangeAxis.setLabelFont(f);
    rangeAxis.setLabelPaint(Color.GRAY);

    va.setRange(0, 6);
    xyplot.setBackgroundPaint(Color.WHITE);
    renderer.setUseOutlinePaint(true);

    Color c0 = new Color(80, 183, 71);
    renderer.setSeriesPaint(0, c0);
    renderer.setSeriesOutlinePaint(0, Color.WHITE);

    Color c1 = new Color(1, 141, 244);
    renderer.setSeriesPaint(1, c1);
    renderer.setSeriesOutlinePaint(1, Color.WHITE);

    Color c2 = new Color(204, 0, 0);
    renderer.setSeriesPaint(2, c2);
    renderer.setSeriesOutlinePaint(2, Color.WHITE);

    renderer.setSeriesPaint(3, Color.decode("#b5babb"));
    renderer.setSeriesOutlinePaint(3, Color.WHITE);

    renderer.setSeriesPaint(4, new Color(150, 212, 145));
    renderer.setSeriesOutlinePaint(4, new Color(150, 212, 145));

    renderer.setSeriesPaint(5, new Color(103, 187, 248));
    renderer.setSeriesOutlinePaint(5, new Color(103, 187, 248));

    renderer.setSeriesPaint(6, new Color(224, 102, 102));
    renderer.setSeriesOutlinePaint(6, new Color(224, 102, 102));

    renderer.setSeriesPaint(7, Color.decode("#b5babb"));
    renderer.setSeriesOutlinePaint(7, Color.GRAY);

    //        renderer.setSeriesPaint(6, Color.BLACK);
    //        renderer.setSeriesOutlinePaint(6, Color.BLACK);
    Shape downArr = ShapeUtilities.createDownTriangle(7f);
    Shape notRShape = ShapeUtilities.createDiamond(7f);
    Shape upArr = ShapeUtilities.createUpTriangle(7);

    Shape downArrII = ShapeUtilities.createTranslatedShape(ShapeUtilities.createDownTriangle(6f), 5, -5);
    Shape notRShapeII = ShapeUtilities.createTranslatedShape(ShapeUtilities.createDiamond(6f), 0, -7);
    Shape upArrII = ShapeUtilities.createTranslatedShape(ShapeUtilities.createUpTriangle(6f), 4, -4);

    //        Shape plus = ShapeUtilities.createTranslatedShape(ShapeUtilities.createRegularCross(3f, 0.4f), 11, -7);
    renderer.setSeriesShape(0, downArr);
    renderer.setSeriesShape(1, notRShape);
    renderer.setSeriesShape(2, upArr);

    renderer.setSeriesShape(3, notRShape);

    renderer.setSeriesShape(4, downArrII);
    renderer.setSeriesShape(5, notRShapeII);
    renderer.setSeriesShape(6, upArrII);

    renderer.setSeriesShape(7, notRShapeII);
    //       renderer.setSeriesShape(6, plus);

    renderer.setBaseItemLabelsVisible(true);
    renderer.setBaseItemLabelGenerator(new SymbolicXYItemLabelGenerator() {
        private final int[] indexer = new int[] { 0, 1, 2, 3, 0, 1, 2, 3 };

        @Override
        public String generateLabel(XYDataset dataset, int series, int category) {
            if (series > 3) {
                int patNumber = (int) dataset.getYValue(series, category);
                //                    int trend = (int) dataset.getXValue(series, category);
                if (series == 7 || series == 5) {
                    return "\t  " + paTGrNumbtrendMap.get(patNumber)[indexer[series]];
                } else {
                    return "\t   " + paTGrNumbtrendMap.get(patNumber)[indexer[series]];
                }

            }

            return ""; //To change body of generated methods, choose Tools | Templates.
        }

    });
    ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT,
            TextAnchor.TOP_LEFT, 0.0);

    renderer.setSeriesPositiveItemLabelPosition(4, position);
    renderer.setSeriesPositiveItemLabelPosition(5, position);
    renderer.setSeriesPositiveItemLabelPosition(6, position);
    renderer.setSeriesPositiveItemLabelPosition(7, position);

    renderer.setBaseItemLabelFont(f);

    tempScatterPlot.setBorderVisible(false);

    xyplot.setSeriesRenderingOrder(SeriesRenderingOrder.REVERSE);

    heighlightedScatterPlottImgUrl = saveToFile(tempScatterPlot, w, h, defaultScatterPlotRenderingInfo);

    xyplot.setBackgroundPaint(Color.WHITE);
    defaultScatterPlottImgUrl = saveToFile(tempScatterPlot, w, h, defaultScatterPlotRenderingInfo);

    //        xyplot.setBackgroundPaint(c);

    if (custTrend != -1) {
        domainAxis.setGridBandsVisible(true);
        if (custTrend == 4) {
            domainAxis.setGridBandPaint(Color.decode("#ffe5e5"));
            xyplot.setDomainTickBandPaint(Color.decode("#ffe5e5"));
            domainAxis.setGridBandAlternatePaint(Color.decode("#ffe5e5"));
        } else if (custTrend == 0) {
            domainAxis.setGridBandPaint(Color.decode("#e5ffe5"));
            xyplot.setDomainTickBandPaint(c);
        } else if (custTrend == 2) {
            domainAxis.setGridBandPaint(Color.decode("#e6f4ff"));
            xyplot.setDomainTickBandPaint(c);
        }

    }

    String textTitle = comparisonTitle.getValue().split("bold;'>")[1].replace("</font>", "");
    TextTitle title = new TextTitle(textTitle, f);

    scatterPlot = new JFreeChart(xyplot);
    scatterPlot.setTitle(title);

    scatterPlot.setBorderVisible(false);
    scatterPlot.setBackgroundPaint(Color.WHITE);
    scatterPlot.getLegend().setVisible(false);
    dsKeyDatasetMap.clear();
    for (int i = 0; i < defaultScatterPlotRenderingInfo.getEntityCollection().getEntityCount(); i++) {
        final ChartEntity entity = defaultScatterPlotRenderingInfo.getEntityCollection().getEntity(i);
        if (entity instanceof XYItemEntity) {

            int x = ((XYItemEntity) entity).getSeriesIndex();
            int y = ((XYItemEntity) entity).getItem();

            if (((XYItemEntity) entity).getDataset().getYValue(x,
                    y) > (int) ((XYItemEntity) entity).getDataset().getYValue(x, y)) {
                continue;
            }
            if (((XYItemEntity) entity).getSeriesIndex() > 3) {

                continue;
            }

            String[] arr = ((XYItemEntity) entity).getShapeCoords().split(",");
            int xSer = Integer.valueOf(arr[0]);
            int ySer = Integer.valueOf(arr[1]);
            int ySerEnd = Integer.valueOf(arr[3]);
            int patGrNumber = (int) ((XYItemEntity) entity).getDataset().getYValue(x, y);
            int trend = Integer.valueOf(((XYItemEntity) entity).getDataset()
                    .getSeriesKey(((XYItemEntity) entity).getSeriesIndex()).toString());

            ComparisonDetailsBean cpDetails = patientGroupsNumToDsIdMap.get(patGrNumber);
            List<Integer> dsList = cpDetails.getRegulatedList(trend);
            StringBuilder sb = new StringBuilder();

            for (int dsId : dsList) {
                QuantDatasetObject ds;

                sb.append("<h4>").append((Quant_Central_Manager.getFullQuantDatasetMap().get(dsId)).getAuthor())
                        .append(" ")
                        .append((Quant_Central_Manager.getFullQuantDatasetMap().get(dsId)).getYear())
                        .append("<h4/>");
                sb.append("<p></p>");
                ds = Quant_Central_Manager.getFullQuantDatasetMap().get(dsId);

                dsKeyDatasetMap.put("_-_" + dsId + "_-_" + comparisonProtein.getProteinAccssionNumber() + "_-_",
                        ds);
            }
            String tooltip = sb.toString().substring(0, sb.toString().length() - 7);
            SquaredDot square = new SquaredDot("squared");
            if (paTGrNumbtrendMap.get(patGrNumber)[trend] > 1) {
                square.setWidth(20 + "px");
                square.setHeight(15 + "px");
            } else {
                square.setWidth(10 + "px");
                square.setHeight(10 + "px");
            }
            square.setDescription(tooltip);
            square.setParam("trend", trend);
            square.setParam("pGrNumber", patGrNumber);
            int top = (ySer - 4);
            if (ySer > ySerEnd) {
                top = ySerEnd - 3;
            }
            defaultChartLayout.addComponent(square, "left: " + (xSer - 5) + "px; top: " + top + "px;");
        }
    }

}

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

public void createGraph(PlotJob job, Map<String, List<Double>> PFTData, Map<String, List<Double>> data,
        List<LogEvent> events, List<SEAction> actions) {
    CSVPlotTool plotTool = new CSVPlotTool(); //to leverage existing functions
    String title = job.name + "_";
    XYSeriesCollection dataSet = new XYSeriesCollection();
    double maxY = 0;
    double minY = Double.MAX_VALUE;
    for (int i = 0; i < job.headers.size(); i++) {
        title = title + job.headers.get(i) + "_";
        XYSeries dataSeries;/*from  w  w  w .  ja va  2 s.  c  o  m*/
        dataSeries = plotTool.createXYSeries(job.headers.get(i), data.get("Time(s)"),
                data.get(job.headers.get(i)));
        dataSet.addSeries(dataSeries);
        maxY = maxY < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY;
        minY = minY > dataSeries.getMinY() ? dataSeries.getMinY() : minY;
    }

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

    title = title + "vs_Time";

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

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

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

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

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

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

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

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

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

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

            allActionsAndEvents.add(entry);
        }
    }

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

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

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

            AEEntry entry = new AEEntry();

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

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

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

            allActionsAndEvents.add(entry);
        }
    }

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

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

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

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

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

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

        //Add another Y axis to the right side for easier reading
        ValueAxis rightYAxis = new NumberAxis();
        rightYAxis.setRange(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength);
        rightYAxis.setLabel("");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:edu.umn.ecology.populus.plot.BasicPlotInfo.java

public ChartTheme getJFreeChartTheme() {
    class PopChartTheme implements ChartTheme {
        private BasicPlotInfo bpiRef;

        public PopChartTheme(BasicPlotInfo bpi) {
            this.bpiRef = bpi;
        }/*from   w ww  . j  av a  2s.c  o  m*/

        public void apply(JFreeChart chart) {
            JFCXYAdapter jfca = new JFCXYAdapter();
            XYPlot plot = chart.getXYPlot();
            plot.setDataset(jfca);

            if (isLogPlot) {
                plot.setRangeAxis(new LogarithmicAxis(""));
            }
            if (isFrequencies) {
                ValueAxis va = plot.getRangeAxis();
                if (va instanceof NumberAxis) {
                    NumberAxis na = (NumberAxis) va;
                    na.setTickUnit(new NumberTickUnit(0.1));
                } else {
                    Logging.log("Range Axis is not NumberAxis, why?", Logging.kWarn);
                }
            }

            if (xMinSet)
                plot.getDomainAxis().setLowerBound(xAxisMin);
            if (xMaxSet)
                plot.getDomainAxis().setUpperBound(xAxisMax);
            if (yMinSet)
                plot.getRangeAxis().setLowerBound(yAxisMin);
            if (yMaxSet)
                plot.getRangeAxis().setUpperBound(yAxisMax);

            //TODO - just use this renderer
            plot.setRenderer(new ChartRendererWithOrientatedShapes(bpiRef));

            XYItemRenderer r = plot.getRenderer();
            //         AbstractXYItemRenderer r = plot.getRenderer();
            if (r instanceof XYLineAndShapeRenderer) {
                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
                for (int i = 0; i < getNumSeries(); i++) {
                    //Set Line
                    renderer.setSeriesPaint(i, getLineColor(i));
                    renderer.setSeriesStroke(i, getLineStroke(i));

                    //Set Symbol
                    renderer.setSeriesFillPaint(i, getSymbolColor(i));
                    renderer.setSeriesOutlinePaint(i, getSymbolColor(i));

                    Shape shape = getSymbolShape(i);
                    if (shape != null) {
                        renderer.setSeriesShape(i, shape);
                        renderer.setSeriesShapesFilled(i, isSymbolOpaque(i));
                        renderer.setUseFillPaint(true);
                        renderer.setUseOutlinePaint(true);
                        renderer.setSeriesShapesVisible(i, true);
                    }
                }
            } else if (r instanceof XYBarRenderer) {
                XYBarRenderer barRenderer = (XYBarRenderer) r;
                barRenderer.setBarPainter(new StandardXYBarPainter());
            } else {
                Logging.log("Unknown renderer type: " + r.getClass(), Logging.kWarn);
            }

            //inner labels, used in AIDS: Therapy
            plot.clearAnnotations();
            Enumeration<InnerLabel> e = innerLabels.elements();
            while (e.hasMoreElements()) {
                InnerLabel lab = (InnerLabel) e.nextElement();
                Logging.log("Adding " + lab.caption + " at " + lab.x + ", " + lab.y);

                XYTextAnnotation annotation = new XYTextAnnotation(lab.caption, lab.x, lab.y);
                annotation.setTextAnchor(TextAnchor.BOTTOM_CENTER);
                annotation.setOutlineVisible(true);
                plot.addAnnotation(annotation);

                //I actually think the annotation above is ugly.  We can use one of these instead in the future, maybe...
                /*PointerAnnotation may look cool...
                 * That 2.0 is the angle, randomly picked
                 * XYPointerAnnotation annotation = new XYPointerAnnotation(lab.caption, lab.x, lab.y, 2.0); 
                 */

                /*
                ValueMarker marker = new ValueMarker(lab.x);
                marker.setLabel(lab.caption);
                marker.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT);
                plot.addDomainMarker(marker);
                 */

            }

            //This is set for GD: AMCM
            if (startGridded) {
                plot.setDomainGridlinesVisible(true);
                plot.setDomainGridlinePaint(Color.BLACK);
                plot.setRangeGridlinesVisible(true);
                plot.setRangeGridlinePaint(Color.BLACK);
            }

        }
    }
    return new PopChartTheme(this);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

            allActionsAndEvents.add(entry);
        }
    }

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

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

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

            AEEntry entry = new AEEntry();

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

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

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

            allActionsAndEvents.add(entry);
        }
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        }

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

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

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

@Override
public void plot(LogListener listener, SESubstanceManager subMgr) {
    //fill PlotJob with needed data if it doesn't exist
    PlotJob job = (PlotJob) listener;//ww w  .ja v a2s.c  o m
    if (job.dataPath == null || job.dataPath.isEmpty()) {
        job.dataPath = "../verification/Scenarios/" + job.verificationDirectory + "/Current Baseline/";
    }
    if (job.dataFile == null || job.dataFile.isEmpty()) {
        job.dataFile = job.name + "Results.zip";
    }

    //Get data contents for all headers when all data is in one file
    if ((data.isEmpty() || data == null) && job.experimentalData == null) {
        try {
            CSVContents csv = new CSVContents(job.dataPath + job.dataFile);
            csv.abbreviateContents = job.resultsSkipNum;
            for (int i = 0; i < job.headers.size(); i++) {
                List<Double> headerData = new ArrayList<Double>();
                csv.readHeader(csv.unitUnderscoreToSpace(job.headers.get(i)), headerData);
                data.put(job.headers.get(i), headerData);
            }
        } catch (IOException e) {
            Log.error("Could not analyze file " + job.dataPath + job.dataFile);
        }
    }
    //Get data contents when we're also using experimental files
    else if ((data.isEmpty() || data == null) && job.experimentalData != null) {
        CSVContents dataCsv = null;
        CSVContents expCsv = null;

        try {
            dataCsv = new CSVContents(job.dataPath + job.dataFile);
            dataCsv.abbreviateContents = job.resultsSkipNum;
        } catch (IOException e) {
            Log.error("Could not analyze file " + job.dataPath + job.dataFile);
        }
        try {
            expCsv = new CSVContents(job.experimentalData);
            expCsv.abbreviateContents = 0; //we'll use all of the experimental data
        } catch (IOException e) {
            Log.error("Could not analyze file " + job.experimentalData);
        }
        try {
            //Get data from X1 and Y1, which should always be from our normal data file
            for (int i = 0; i < job.Y1headers.size(); i++) {
                List<Double> headerData = new ArrayList<Double>();
                dataCsv.readHeader(dataCsv.unitUnderscoreToSpace(job.Y1headers.get(i)), headerData);
                data.put(job.Y1headers.get(i), headerData);
            }
            List<Double> headerData = new ArrayList<Double>();
            dataCsv.readHeader(dataCsv.unitUnderscoreToSpace(job.X1header), headerData);
            data.put(job.X1header, headerData);

            for (int i = 0; i < job.Y2headers.size(); i++) {
                List<Double> headerData2 = new ArrayList<Double>();
                expCsv.readHeader(expCsv.unitUnderscoreToSpace(job.Y2headers.get(i)), headerData2);
                expData.put(job.Y2headers.get(i), headerData2);
            }
            List<Double> headerData2 = new ArrayList<Double>();
            expCsv.readHeader(expCsv.unitUnderscoreToSpace(job.X2header), headerData2);
            expData.put(job.X2header, headerData2);
        } catch (Exception e) {
            Log.error("A problem was encountered reading headers from files.");
        }
    }

    //Catch some errors
    if (job.Y2headers.size() > 0 && job.X2header == null) {
        Log.error("No X2 header specified for job " + job.name
                + ". Each Y axis must have a corresponding X axis.");
        return;
    }

    //Make a dataSeries for desired headers and add to collection(s)
    CSVPlotTool plotTool = new CSVPlotTool(); //to leverage existing functions
    String title = job.name + "_";
    XYSeriesCollection dataSet1 = new XYSeriesCollection();
    XYSeriesCollection dataSet2 = new XYSeriesCollection();
    double maxY1 = 0;
    double minY1 = Double.MAX_VALUE;
    double maxY2 = 0;
    double minY2 = Double.MAX_VALUE;
    for (int i = 0; i < job.Y1headers.size(); i++) {
        XYSeries dataSeries;
        if (job.experimentalData != null)
            dataSeries = plotTool.createXYSeries("BioGears " + job.Y1headers.get(i), data.get(job.X1header),
                    data.get(job.Y1headers.get(i)));
        else
            dataSeries = plotTool.createXYSeries(job.Y1headers.get(i), data.get(job.X1header),
                    data.get(job.Y1headers.get(i)));
        dataSet1.addSeries(dataSeries);
        title = title + job.Y1headers.get(i) + "_";
        maxY1 = maxY1 < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY1;
        minY1 = minY1 > dataSeries.getMinY() ? dataSeries.getMinY() : minY1;
    }
    for (int i = 0; i < job.Y2headers.size(); i++) {
        XYSeries dataSeries;
        if (job.experimentalData != null)
            dataSeries = plotTool.createXYSeries("Experimental " + job.Y2headers.get(i),
                    expData.get(job.X2header), expData.get(job.Y2headers.get(i)));
        else
            dataSeries = plotTool.createXYSeries(job.Y2headers.get(i), data.get(job.X2header),
                    data.get(job.Y2headers.get(i)));
        dataSet2.addSeries(dataSeries);
        title = title + job.Y2headers.get(i) + "_";
        maxY2 = maxY2 < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY2;
        minY2 = minY2 > dataSeries.getMinY() ? dataSeries.getMinY() : minY2;
    }
    title = title + "vs_" + job.X1header;
    if (job.X2header != null && !job.X1header.equalsIgnoreCase(job.X2header))
        title = title + "_" + job.X2header;

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

    //set labels
    String XAxisLabel = job.X1header;
    String YAxisLabel = job.Y1headers.get(0);

    JFreeChart chart = ChartFactory.createXYLineChart(
            job.titleOverride != null && job.titleOverride.equalsIgnoreCase("None") ? "" : title, // chart title
            XAxisLabel, // x axis label
            YAxisLabel, // y axis label
            dataSet1, // 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 Y1 range
        double resMax0 = maxY1;
        double resMin0 = minY1;
        if (Double.isNaN(resMax0) || Double.isNaN(resMin0))
            plot.getDomainAxis(0).setLabel("Range is NaN");
        if (DoubleUtils.isZero(resMin0))
            resMin0 = -0.001;
        if (DoubleUtils.isZero(resMax0))
            resMax0 = 0.001;
        double rangeLength = resMax0 - resMin0;
        ValueAxis yAxis = plot.getRangeAxis(0);
        if (rangeLength != 0)
            yAxis.setRange(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength);//15% buffer so we can see top and bottom clearly  

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null)
                yAxis.setLowerBound(job.Y1LowerBound);
            if (job.Y1UpperBound != null)
                yAxis.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);

        //Add the second Y axis to the right side
        if (!job.Y2headers.isEmpty()) {
            ValueAxis rightYAxis = new NumberAxis();
            // Determine Y2 range
            double resMax1 = maxY2;
            double resMin1 = minY2;
            if (Double.isNaN(resMax1) || Double.isNaN(resMin1))
                plot.getDomainAxis(1).setLabel("Range is NaN");
            if (DoubleUtils.isZero(resMin1))
                resMin1 = -0.001;
            if (DoubleUtils.isZero(resMax1))
                resMax1 = 0.001;
            rangeLength = resMax1 - resMin1;
            if (rangeLength != 0)
                rightYAxis.setRange(resMin1 - 0.15 * rangeLength, resMax1 + 0.15 * rangeLength);
            rightYAxis.setLabel(job.Y2headers.get(0));

            //Override the bounds if desired
            try {
                if (job.Y2LowerBound != null)
                    rightYAxis.setLowerBound(job.Y2LowerBound);
                if (job.Y2UpperBound != null)
                    rightYAxis.setUpperBound(job.Y2UpperBound);
            } 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(1, rightYAxis);
        }
    } else {
        double resMin = minY1 < minY2 ? minY1 : minY2;
        if (resMin <= 0.0)
            resMin = .00001;
        LogarithmicAxis yAxis = new LogarithmicAxis("Log(" + YAxisLabel + ")");
        yAxis.setLowerBound(resMin);

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null)
                yAxis.setLowerBound(job.Y1LowerBound);
            if (job.Y1UpperBound != null)
                yAxis.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);

        if (!job.Y2headers.isEmpty()) {
            LogarithmicAxis rightYAxis = new LogarithmicAxis("Log(" + job.Y2headers.get(0) + ")");
            rightYAxis.setLowerBound(resMin);

            //Override the bounds if desired
            try {
                if (job.Y2LowerBound != null)
                    rightYAxis.setLowerBound(job.Y2LowerBound);
                if (job.Y2UpperBound != null)
                    rightYAxis.setUpperBound(job.Y2UpperBound);
            } 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(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);
        if (job.X2LowerBound != null)
            plot.getDomainAxis(1).setLowerBound(job.X2LowerBound);
        if (job.X2UpperBound != null)
            plot.getDomainAxis(1).setUpperBound(job.X2UpperBound);
    } catch (Exception e) {
        Log.error("Couldn't set X bounds. You probably tried to set a bound on an axis that doesn't exist.");
    }

    //Add the second dataset if necessary
    if (!job.Y2headers.isEmpty()) {
        plot.setDataset(1, dataSet2);
        plot.mapDatasetToRangeAxis(1, 1);
    }

    //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.X2Label != null && plot.getDomainAxis(1) != null)
        plot.getDomainAxis(1).setLabel(job.X2Label.equalsIgnoreCase("None") ? "" : job.X2Label);
    if (job.Y1Label != null)
        plot.getRangeAxis(0).setLabel(job.Y1Label.equalsIgnoreCase("None") ? "" : job.Y1Label);
    if (job.Y2Label != null && plot.getRangeAxis(1) != null)
        plot.getRangeAxis(1).setLabel(job.Y2Label.equalsIgnoreCase("None") ? "" : job.Y2Label);

    //Format lines and colors
    plot.setDomainGridlinesVisible(job.showGridLines);
    plot.setRangeGridlinesVisible(job.showGridLines);
    formatMultiPlot(job, chart, dataSet1, dataSet2);

    //Handle legends
    if (job.removeAllLegends)
        chart.removeLegend();

    //Make the file
    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
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, 800);
    } catch (IOException e) {
        Log.error(e.getMessage());
    }

}