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

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

Introduction

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

Prototype

public void setSeriesPaint(int series, Paint paint) 

Source Link

Document

Sets the paint used for a series and sends a RendererChangeEvent to all registered listeners.

Usage

From source file:org.pentaho.plugin.jfreereport.reportcharts.XYAreaLineChartExpression.java

protected void configureChart(final JFreeChart chart) {
    super.configureChart(chart);

    final XYPlot plot = chart.getXYPlot();

    if (isSharedRangeAxis() == false) {
        final ValueAxis linesAxis = plot.getRangeAxis(1);
        if (linesAxis instanceof NumberAxis) {
            final NumberAxis numberAxis = (NumberAxis) linesAxis;
            numberAxis.setAutoRangeIncludesZero(isLineAxisIncludesZero());
            numberAxis.setAutoRangeStickyZero(isLineAxisStickyZero());

            if (getLinePeriodCount() > 0) {
                if (getLineTicksLabelFormat() != null) {
                    final FastDecimalFormat formatter = new FastDecimalFormat(getLineTicksLabelFormat(),
                            getResourceBundleFactory().getLocale());
                    numberAxis.setTickUnit(new FastNumberTickUnit(getLinePeriodCount(), formatter));
                } else {
                    numberAxis.setTickUnit(new FastNumberTickUnit(getLinePeriodCount()));
                }/*  w  w w . j ava  2  s  .  c o  m*/
            } else {
                if (getLineTicksLabelFormat() != null) {
                    final DecimalFormat formatter = new DecimalFormat(getLineTicksLabelFormat(),
                            new DecimalFormatSymbols(getResourceBundleFactory().getLocale()));
                    numberAxis.setNumberFormatOverride(formatter);
                }
            }
        } else if (linesAxis instanceof DateAxis) {
            final DateAxis numberAxis = (DateAxis) linesAxis;

            if (getLinePeriodCount() > 0 && getLineTimePeriod() != null) {
                if (getLineTicksLabelFormat() != null) {
                    final SimpleDateFormat formatter = new SimpleDateFormat(getLineTicksLabelFormat(),
                            new DateFormatSymbols(getResourceBundleFactory().getLocale()));
                    numberAxis.setTickUnit(new DateTickUnit(getDateUnitAsInt(getLineTimePeriod()),
                            (int) getLinePeriodCount(), formatter));
                } else {
                    numberAxis.setTickUnit(new DateTickUnit(getDateUnitAsInt(getLineTimePeriod()),
                            (int) getLinePeriodCount()));
                }
            } else if (getRangeTickFormatString() != null) {
                final SimpleDateFormat formatter = new SimpleDateFormat(getRangeTickFormatString(),
                        new DateFormatSymbols(getResourceBundleFactory().getLocale()));
                numberAxis.setDateFormatOverride(formatter);
            }
        }

        if (linesAxis != null) {
            final Font labelFont = Font.decode(getLabelFont());
            linesAxis.setLabelFont(labelFont);
            linesAxis.setTickLabelFont(labelFont);

            if (getLineTitleFont() != null) {
                linesAxis.setLabelFont(getLineTitleFont());
            }
            if (getLineTickFont() != null) {
                linesAxis.setTickLabelFont(getLineTickFont());
            }
            final int level = getRuntime().getProcessingContext().getCompatibilityLevel();
            if (ClassicEngineBoot.isEnforceCompatibilityFor(level, 3, 8)) {
                final double lineRangeMinimumVal = lineRangeMinimum == null ? 0 : lineRangeMinimum;
                final double lineRangeMaximumVal = lineRangeMaximum == null ? 0 : lineRangeMaximum;
                if (lineRangeMinimum != null) {
                    linesAxis.setLowerBound(getLineRangeMinimum());
                }
                if (lineRangeMaximum != null) {
                    linesAxis.setUpperBound(getRangeMaximum());
                }
                if (lineRangeMinimumVal == 0 && lineRangeMaximumVal == 1) {
                    linesAxis.setLowerBound(0);
                    linesAxis.setUpperBound(1);
                    linesAxis.setAutoRange(true);
                }
            } else {
                if (lineRangeMinimum != null) {
                    linesAxis.setLowerBound(lineRangeMinimum);
                }
                if (lineRangeMaximum != null) {
                    linesAxis.setUpperBound(lineRangeMaximum);
                }
                linesAxis.setAutoRange(isLineAxisAutoRange());
            }
        }
    }

    final XYLineAndShapeRenderer linesRenderer = (XYLineAndShapeRenderer) plot.getRenderer(1);
    if (linesRenderer != null) {
        //set stroke with line width
        linesRenderer.setStroke(translateLineStyle(getLineWidth(), getLineStyle()));
        //hide shapes on line
        linesRenderer.setShapesVisible(isMarkersVisible());
        linesRenderer.setBaseShapesFilled(isMarkersVisible());

        //set colors for each line
        for (int i = 0; i < lineSeriesColor.size(); i++) {
            final String s = (String) lineSeriesColor.get(i);
            linesRenderer.setSeriesPaint(i, parseColorFromString(s));
        }
    }
}

From source file:edu.ucla.stat.SOCR.analyses.gui.Chart.java

private JFreeChart createLineChart(String title, String xLabel, String yLabel, XYDataset dataset,
        Color[] colors, String other) {

    // create the chart...
    JFreeChart chart = ChartFactory.createXYLineChart(title, // chart title
            xLabel, // domain axis label
            yLabel, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );/* ww w . j a  v a  2s  .c  om*/

    XYPlot plot = chart.getXYPlot();
    chart.setBackgroundPaint(Color.white);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.lightGray);
    //plot.setNoDataMessage("No data available");

    // customise the range axis...

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
    domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setUpperMargin(0.02);
    rangeAxis.setLowerMargin(0.02);
    domainAxis.setUpperMargin(0.02);
    domainAxis.setLowerMargin(0.02);

    // customise the renderer...
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setBaseShapesVisible(true);
    renderer.setBaseLinesVisible(true);
    renderer.setDrawOutlines(true);
    renderer.setBaseShapesFilled(true);
    renderer.setUseFillPaint(true);
    renderer.setBaseFillPaint(Color.white);

    for (int i = 0; i < colors.length; i++) {
        renderer.setSeriesPaint(i, colors[i]);
    }

    if (other.toLowerCase().indexOf("noline") != -1) {
        renderer.setBaseShapesVisible(true);
        renderer.setBaseLinesVisible(false);
    }

    if (other.toLowerCase().indexOf("noshape") != -1) {
        renderer.setBaseShapesVisible(false);
        renderer.setBaseLinesVisible(true);
    }

    if (other.toLowerCase().indexOf("excludeszero") != -1) {
        rangeAxis.setAutoRangeIncludesZero(false);
        domainAxis.setAutoRangeIncludesZero(false);
    }

    if (other.toLowerCase().indexOf("color") != -1) {
        renderer.setBaseShapesVisible(false);
        renderer.setBaseLinesVisible(true);
    }

    return chart;
}

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

public void createGraph(String toDir, Paint color, String title, String XAxisLabel, String YAxisLabel,
        XYSeries... xyData) {/*  w  w  w  . j a v a  2 s .  c o m*/
    new File(toDir).mkdir();

    Log.info("Creating Graph " + toDir + "/" + title);
    double resMin0 = 1.e6;
    double resMax0 = -1.e6;
    double resMin1 = 1.e6;
    double resMax1 = -1.e6;

    XYSeriesCollection dataSet = new XYSeriesCollection();
    for (XYSeries data : xyData) {
        if (data != null && !data.isEmpty())
            dataSet.addSeries(data);
    }

    JFreeChart chart = ChartFactory.createXYLineChart(title, // chart title
            XAxisLabel, // x axis label
            YAxisLabel, // y axis label
            dataSet, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    XYPlot plot = (XYPlot) chart.getPlot();
    /* I have residual and error plots turned off, there are some plots that contain these names in their title, and I don't want this code running, need a better way to see if we are doing a special plot rather than title contents
        if(title.contains("Residual"))
        {
          // Make plot symmetric about x axis
          resMax0 = xyData[0].getMaxY();
          resMin0 = xyData[0].getMinY();
          if (Math.abs(xyData[0].getMinY()) > Math.abs(xyData[0].getMaxY()))  resMax0 = Math.abs(resMin0);
          if (Math.abs(xyData[0].getMaxY()) > Math.abs(xyData[0].getMinY()))  resMin0 = -1.0*Math.abs(resMax0);
          if((resMin0==0.0) && (resMax0==0.0))
          {
            resMin0 = -0.00001;
            resMax0 =  0.00001;
          }       
          ValueAxis yAxis = plot.getRangeAxis();
          yAxis.setRange(resMin0 + 0.05*resMin0, resMax0 + 0.05*resMax0);//5% buffer so we can see top and bottom clearly
        }
        else if(title.contains("Error"))
        {
          // Make plot symmetric about x axis
          resMax0 = xyData[0].getMaxY();
          resMin0 = xyData[0].getMinY();
          if((resMin0==0.0) && (resMax0==0.0))
          {
            resMin0 = -0.00001;
            resMax0 =  0.00001;
          }
          if(resMin0>=0.0) resMin0 = -0.01;
          ValueAxis yAxis = plot.getRangeAxis();
          yAxis.setRange(resMin0 + 0.05*resMin0, resMax0 + 0.05*resMax0);//5% buffer so we can see top and bottom clearly
            
          /*
           yAxis.setTickLabelPaint(new Color(1,0,0));
           yAxis.setTickMarkPaint(new Color(1,0,0));
           yAxis.setAxisLinePaint(new Color(1,0,0));
           yAxis.setLabelPaint(new Color(1,0,0));
            
           ValueAxis xAxis = plot.getDomainAxis();
           xAxis.setTickLabelPaint(new Color(1,0,0));
           xAxis.setTickMarkPaint(new Color(1,0,0));
           yAxis.setAxisLinePaint(new Color(1,0,0));
           yAxis.setLabelPaint(new Color(1,0,0));
           *
        }
        else
    */
    {
        if (title.indexOf("Hemoglobin-GlomerularFilterability") > -1)
            System.out.println("stop");
        if (xyData.length > 1) {
            // Make plot symmetric about x axis
            resMax0 = xyData[0].getMaxY();
            resMin0 = xyData[0].getMinY();
            resMax1 = xyData[1].getMaxY();
            resMin1 = xyData[1].getMinY();
            if (resMin1 < resMin0)
                resMin0 = resMin1;
            if (resMax1 > resMax0)
                resMax0 = resMax1;
            if (DoubleUtils.isZero(resMin0))
                resMin0 = -0.001;
            if (DoubleUtils.isZero(resMax0))
                resMax0 = 0.001;
            if (resMin0 >= 0.0)
                resMin0 = -0.01;
            if (YAxisLabel.indexOf("PlasmaConcentration") > -1)
                plot.setRangeAxis(new LogarithmicAxis("Log(" + YAxisLabel + ")"));
            else {
                ValueAxis yAxis = plot.getRangeAxis();
                yAxis.setRange(resMin0 + 0.05 * resMin0, resMax0 + 0.15 * Math.abs(resMax0));//5% buffer so we can see top and bottom clearly
            }
            String NaNCheck = "";
            if (Double.isNaN(resMax0) || Double.isNaN(resMin0))
                NaNCheck += "Expected is NaN ";
            if (Double.isNaN(resMax1) || Double.isNaN(resMin1))
                NaNCheck += "Computed is NaN ";
            if (!NaNCheck.isEmpty())
                plot.getDomainAxis().setLabel(NaNCheck);
        } else {
            // Make plot symmetric about x axis
            resMax0 = xyData[0].getMaxY();
            resMin0 = xyData[0].getMinY();
            if (Double.isNaN(resMax0) || Double.isNaN(resMin0))
                plot.getDomainAxis().setLabel("Computed is NaN");
            if (DoubleUtils.isZero(resMin0))
                resMin0 = -0.001;
            if (DoubleUtils.isZero(resMax0))
                resMax0 = 0.001;
            if (resMin0 >= 0.0)
                resMin0 = -0.01;
            if (YAxisLabel.indexOf("PlasmaConcentration") > -1)
                plot.setRangeAxis(new LogarithmicAxis("Log(" + YAxisLabel + ")"));
            else {
                ValueAxis yAxis = plot.getRangeAxis();
                yAxis.setRange(resMin0 + 0.05 * resMin0, resMax0 + 0.15 * Math.abs(resMax0));//5% buffer so we can see top and bottom clearly
            }
        }
    }

    formatXYPlot(chart, color);
    //Changing line widths and colors
    XYItemRenderer r = plot.getRenderer();
    BasicStroke wideLine = new BasicStroke(lineWidth);
    r.setSeriesStroke(0, wideLine);
    r.setSeriesStroke(1, wideLine);
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    if (xyData.length > 1) {
        renderer.setSeriesStroke(//makes a dashed line
                0, //argument below float[]{I,K} -> alternates between solid and opaque (solid for I, opaque for K)
                new BasicStroke(lineWidth, 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(0, expectedLineColor);
    renderer.setSeriesFillPaint(1, computedLineColor);
    renderer.setSeriesPaint(0, expectedLineColor);
    renderer.setSeriesPaint(1, computedLineColor);

    try {
        if (toDir == null || toDir.isEmpty())
            toDir = ".";
        File JPGFile = new File(toDir + "/" + MakeFileName(title) + ".jpg");
        ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, 800);
    } catch (IOException e) {
        Log.error(e.getMessage());
    }
}

From source file:net.liuxuan.device.VACVBS.JIF_DrawChart_vacvbs.java

/**
 * ?jfreechart//from  w ww .  j  a  v a  2  s .co m
 */
public void initChart() {
    ts_LP = new TimeSeries("LowPressure", Millisecond.class);
    ts_HP = new TimeSeries("HighPressure", Millisecond.class);
    ts_humidity = new TimeSeries("Humidity", Millisecond.class);
    ts_temprature = new TimeSeries("Temperature", Millisecond.class);
    ts_time = new TimeSeries("TestTime", Millisecond.class);
    ts_num = new TimeSeries("num", Millisecond.class);
    ts_reserved1 = new TimeSeries("reserved1", Millisecond.class);
    ts_reserved2 = new TimeSeries("reserved2", Millisecond.class);
    ts_reserved3 = new TimeSeries("reserved3", Millisecond.class);
    trcollection = new TimeSeriesCollection(ts_LP);

    trcollection.addSeries(ts_HP);

    trcollection2 = new TimeSeriesCollection(ts_humidity);

    trcollection2.addSeries(ts_temprature);

    //        trcollection2.addSeries(ts_num);
    //        trcollection2.addSeries(ts_time);
    //trcollection2.addSeries(ts_reserved1);
    //trcollection2.addSeries(ts_reserved2);
    //trcollection2.addSeries(ts_reserved3);

    //        timeseriescopylist.add(getTimeSeries(3).createCopy(0, getTimeSeries(3).getItemCount() - 1));
    JFreeChart jfreechart = ChartFactory.createTimeSeriesChart("", "Time(s)", "PPM", trcollection,
            true, true, false);
    XYPlot xyplot = jfreechart.getXYPlot();

    xyplot.setDomainCrosshairVisible(true);
    xyplot.setRangeCrosshairVisible(true);

    Font fs = new Font("", Font.BOLD, 14);
    Font fs2 = new Font("", Font.BOLD, 12);

    XYLineAndShapeRenderer line0render = (XYLineAndShapeRenderer) xyplot.getRenderer(0);

    Color purple = new Color(139, 0, 255);

    line0render.setSeriesPaint(0, Color.blue);
    line0render.setSeriesPaint(1, Color.green);
    line0render.setSeriesPaint(2, Color.red);
    line0render.setSeriesPaint(3, purple);

    //        line0render.setSeriesPaint(3, Color.ORANGE);
    XYLineAndShapeRenderer line1render = new XYLineAndShapeRenderer();
    Color Rosered = new Color(230, 28, 100);
    line1render.setSeriesPaint(0, Color.cyan);
    line1render.setSeriesPaint(1, Rosered);
    line1render.setSeriesPaint(2, Color.orange);
    line1render.setSeriesPaint(3, Color.yellow);
    line1render.setBaseShapesVisible(false);
    xyplot.setRenderer(1, line1render);

    //??
    ValueAxis valueaxis = xyplot.getDomainAxis();

    //
    valueaxis.setLabelFont(fs);

    //
    valueaxis.setTickLabelFont(fs2);

    ValueAxis valueaxis2 = new NumberAxis("");
    valueaxis2.setLabelFont(fs);
    valueaxis2.setTickLabelFont(fs2);

    xyplot.setRangeAxis(1, valueaxis2);
    xyplot.setDataset(1, trcollection2);
    xyplot.mapDatasetToRangeAxis(1, 1);

    //??
    valueaxis.setAutoRange(true);
    //?? 7days
    //                valueaxis.setFixedAutoRange(604800000D);
    valueaxis = xyplot.getRangeAxis();

    valueaxis.setLabelFont(new Font("", Font.BOLD, 14));
    valueaxis.setLabelPaint(line0render.getSeriesPaint(0));
    valueaxis2.setLabelPaint(line1render.getSeriesPaint(0));

    jfreechart.getTitle().setFont(new Font("", Font.BOLD, 20));//
    jfreechart.getLegend().setItemFont(new Font("", Font.ITALIC, 15));
    xyplot.getRenderer(0).setSeriesToolTipGenerator(0, new StandardXYToolTipGenerator("{1}, {2}",
            new SimpleDateFormat("MM-dd HH:mm:ss"), new DecimalFormat("0.0000")));
    xyplot.getRenderer(1).setSeriesToolTipGenerator(0, new StandardXYToolTipGenerator("{1}, {2}",
            new SimpleDateFormat("MM-dd HH:mm:ss"), new DecimalFormat("0.0000")));
    chartPanel = new ChartPanel(jfreechart);

    initChartMenu();
    //        chartPanel.getPopupMenu().add(jmenuitem2);
    //        chartPanel.getPopupMenu().getPopupMenuListeners();

    chartPanel.setSize(950, 620);
    chartPanel.setPreferredSize(new Dimension(950, 620));
    jPanel_Show.add(chartPanel, BorderLayout.CENTER);
}

From source file:de.uka.aifb.com.systemDynamics.gui.ModelExecutionChartPanel.java

/**
 * Creates panel.//from w  w  w . j av  a  2s  .c o  m
 */
private void createPanel() {
    setLayout(new BorderLayout());

    // CENTER: chart
    ChartPanel chartPanel = new ChartPanel(createChart());
    // no context menu
    chartPanel.setPopupMenu(null);
    // not zoomable
    chartPanel.setMouseZoomable(false);
    add(chartPanel, BorderLayout.CENTER);

    // LINE_END: series table
    JPanel tablePanel = new JPanel(new GridBagLayout());
    String[] columnNames = { messages.getString("ModelExecutionChartPanel.Table.ColumnNames.ExtraAxis"),
            messages.getString("ModelExecutionChartPanel.Table.ColumnNames.LevelNode") };
    final MyTableModel tableModel = new MyTableModel(columnNames, xySeriesArray.length);
    for (int i = 0; i < xySeriesArray.length; i++) {
        tableModel.addEntry((String) xySeriesArray[i].getKey());
    }
    JTable table = new JTable(tableModel);
    table.setRowSelectionAllowed(false);
    JScrollPane tableScrollPane = new JScrollPane(table);
    int width = (int) Math.min(300, table.getPreferredSize().getWidth());
    int height = (int) Math.min(200, table.getPreferredSize().getHeight());
    tableScrollPane.getViewport().setPreferredSize(new Dimension(width, height));
    tableScrollPane.setMaximumSize(tableScrollPane.getViewport().getPreferredSize());
    axesButton = new JButton(messages.getString("ModelExecutionChartPanel.AxesButton.Text"));
    axesButton.setToolTipText(messages.getString("ModelExecutionChartPanel.AxesButton.ToolTipText"));
    axesButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // create XYSeriesCollections (and renderer)
            XYSeriesCollection standardData = new XYSeriesCollection();
            XYLineAndShapeRenderer standardRenderer = new XYLineAndShapeRenderer(true, false);
            LinkedList<XYSeriesCollection> extraDataList = new LinkedList<XYSeriesCollection>();
            LinkedList<XYLineAndShapeRenderer> extraRendererList = new LinkedList<XYLineAndShapeRenderer>();
            for (int i = 0; i < tableModel.getRowCount(); i++) {
                if (tableModel.getValueAt(i, 0).equals(Boolean.FALSE)) {
                    standardData.addSeries(xySeriesArray[i]);
                    standardRenderer.setSeriesPaint(standardData.getSeriesCount() - 1,
                            DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[i
                                    % DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length]);
                } else {
                    // extra axis
                    XYSeriesCollection extraData = new XYSeriesCollection();
                    extraData.addSeries(xySeriesArray[i]);
                    extraDataList.add(extraData);
                    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
                    extraRendererList.add(renderer);
                    renderer.setSeriesPaint(0, DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[i
                            % DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length]);
                }
            }
            LinkedList<XYSeriesCollection> dataList = new LinkedList<XYSeriesCollection>();
            LinkedList<XYLineAndShapeRenderer> rendererList = new LinkedList<XYLineAndShapeRenderer>();
            if (!standardData.getSeries().isEmpty()) {
                dataList.add(standardData);
                rendererList.add(standardRenderer);
            }
            for (XYSeriesCollection data : extraDataList) {
                dataList.add(data);
            }
            for (XYLineAndShapeRenderer renderer : extraRendererList) {
                rendererList.add(renderer);
            }

            // creates axes
            LinkedList<NumberAxis> axesList = new LinkedList<NumberAxis>();
            if (!standardData.getSeries().isEmpty()) {
                NumberAxis axis = new NumberAxis(messages.getString("ModelExecutionChartPanel.Value"));
                axis.setNumberFormatOverride(NumberFormat.getInstance(locale));
                axesList.add(axis);
            }
            for (XYSeriesCollection data : extraDataList) {
                NumberAxis axis = new NumberAxis((String) data.getSeries(0).getKey());
                axis.setNumberFormatOverride(NumberFormat.getInstance(locale));
                axesList.add(axis);
            }

            // store data and axes in plot
            XYPlot plot = chart.getXYPlot();
            plot.clearRangeAxes();
            plot.setRangeAxes(axesList.toArray(new NumberAxis[0]));
            for (int i = 0; i < plot.getDatasetCount(); i++) {
                plot.setDataset(i, null);
            }
            int datasetIndex = 0;
            Iterator<XYSeriesCollection> datasetIterator = dataList.iterator();
            Iterator<XYLineAndShapeRenderer> rendererIterator = rendererList.iterator();
            while (datasetIterator.hasNext()) {
                plot.setDataset(datasetIndex, datasetIterator.next());
                plot.setRenderer(datasetIndex, rendererIterator.next());
                datasetIndex++;
            }
            for (int i = 0; i < plot.getDatasetCount(); i++) {
                plot.mapDatasetToRangeAxis(i, i);
            }
        }
    });
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.CENTER;
    c.gridx = 0;
    c.gridy = 0;
    c.insets = new Insets(0, 0, 10, 0);
    tablePanel.add(tableScrollPane, c);
    c.gridx = 0;
    c.gridy = 1;
    tablePanel.add(axesButton, c);
    add(tablePanel, BorderLayout.LINE_END);

    // PAGE_END: number of rounds and execution button
    JPanel commandPanel = new JPanel();
    commandPanel.add(new JLabel(messages.getString("ModelExecutionChartPanel.NumberRounds")));
    final JTextField numberRoundsField = new JTextField("1", 5);
    numberRoundsField.addFocusListener(this);
    commandPanel.add(numberRoundsField);
    executionButton = new JButton(messages.getString("ModelExecutionChartPanel.ExecutionButton.Text"));
    executionButton.setToolTipText(messages.getString("ModelExecutionChartPanel.ExecutionButton.ToolTipText"));
    executionButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int numberRounds = 0;
            boolean correctNumber = false;
            try {
                numberRounds = integerNumberFormatter.parse(numberRoundsField.getText()).intValue();
            } catch (ParseException parseExcep) {
                // do nothing
            }

            if (numberRounds >= 1) {
                correctNumber = true;
            }

            if (correctNumber) {
                ModelExecutionThread executionThread = new ModelExecutionThread(numberRounds);
                executionThread.start();
            } else {
                JOptionPane.showMessageDialog(null,
                        messages.getString("ModelExecutionChartPanel.Error.Message"),
                        messages.getString("ModelExecutionChartPanel.Error.Title"), JOptionPane.ERROR_MESSAGE);
            }
        }
    });
    commandPanel.add(executionButton);
    add(commandPanel, BorderLayout.PAGE_END);
}

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

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

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

    title = title + "vs_Time";

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

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

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

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

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

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

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

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

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

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

            allActionsAndEvents.add(entry);
        }
    }

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

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

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

            AEEntry entry = new AEEntry();

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

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

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

            allActionsAndEvents.add(entry);
        }
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:projects.wdlf47tuc.ProcessAllSwathcal.java

/**
 * Plots the CMD using the existing dataset. Used whenever chart annotations change, without the
 * underlying plot data changing. This method identifies all sources lying within the boxed region
 * and loads them into the secondary list {@link #boxedSources}.
 * /*from  w ww.j av  a  2  s.  co m*/
 * @param allSources
 *    The {@link Source}s to plot
 * @return
 *    A JFreeChart presenting the colour-magnitude diagram for the current selection criteria and colours.
 */
private JFreeChart plotCmd() {

    XYSeries outside = new XYSeries("Outside");
    XYSeries inside = new XYSeries("Inside");

    // Use a Path2D.Double instance to determine polygon intersection
    Path2D.Double path = new Path2D.Double();
    boxedSources.clear();

    boolean performBoxSelection = (points.size() > 2);

    if (performBoxSelection) {
        // Initialise Path2D object
        path.moveTo(points.get(0)[0], points.get(0)[1]);
        for (double[] point : points) {
            path.lineTo(point[0], point[1]);
        }
    }

    for (Source source : selectedSources) {
        double magnitude = source.getMag(magFilter);
        double col1 = source.getMag(col1Filter);
        double col2 = source.getMag(col2Filter);

        double x = col1 - col2;
        double y = magnitude;

        if (performBoxSelection) {
            Point2D.Double point = new Point2D.Double(x, y);
            if (path.contains(point)) {
                inside.add(x, y);
                boxedSources.add(source);
            } else {
                outside.add(x, y);
            }
        } else {
            outside.add(x, y);
        }
    }

    final XYSeriesCollection data = new XYSeriesCollection();
    data.addSeries(outside);
    data.addSeries(inside);

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer.setSeriesLinesVisible(0, false);
    renderer.setSeriesShapesVisible(0, true);
    renderer.setSeriesShape(0, new Ellipse2D.Float(-0.5f, -0.5f, 1, 1));
    renderer.setSeriesPaint(0, ChartColor.BLACK);

    renderer.setSeriesLinesVisible(1, false);
    renderer.setSeriesShapesVisible(1, true);
    renderer.setSeriesShape(1, new Ellipse2D.Float(-0.5f, -0.5f, 1, 1));
    renderer.setSeriesPaint(1, ChartColor.RED);

    NumberAxis xAxis = new NumberAxis(col1Filter.toString() + " - " + col2Filter.toString());
    xAxis.setRange(getXRange());

    NumberAxis yAxis = new NumberAxis(magFilter.toString());
    yAxis.setRange(getYRange());
    yAxis.setInverted(true);

    // Configure plot
    XYPlot xyplot = new XYPlot(data, xAxis, yAxis, renderer);
    xyplot.setBackgroundPaint(Color.lightGray);
    xyplot.setDomainGridlinePaint(Color.white);
    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.white);

    // Specify selection box, if points have been specified
    if (!points.isEmpty()) {

        double[] coords = new double[points.size() * 2];

        for (int i = 0; i < points.size(); i++) {
            double[] point = points.get(i);
            coords[2 * i + 0] = point[0];
            coords[2 * i + 1] = point[1];
        }
        XYPolygonAnnotation box = new XYPolygonAnnotation(coords, new BasicStroke(2.0f), Color.BLUE);
        xyplot.addAnnotation(box);
    }

    // Configure chart
    JFreeChart chart = new JFreeChart("47 Tuc CMD", xyplot);
    chart.setBackgroundPaint(Color.white);
    chart.setTitle("47 Tuc colour-magnitude diagram");
    chart.removeLegend();

    return chart;
}

From source file:org.gbif.portal.web.controller.dataset.IndexingHistoryController.java

/**
 * Create a time series graphic to display indexing processes.
 * /*from  ww  w. ja v  a 2 s.  c o  m*/
 * @param dataProvider
 * @param dataResource
 * @param activities
 * @param fileNamePrefix
 * @return
 */
public String timeSeriesTest(DataProviderDTO dataProvider, DataResourceDTO dataResource,
        List<LoggedActivityDTO> loggedActivities, String fileNamePrefix, int minProcessingTimeToRender) {

    List<LoggedActivityDTO> activities = new ArrayList<LoggedActivityDTO>();
    for (LoggedActivityDTO la : loggedActivities) {
        if (la.getDataResourceKey() != null && la.getDataResourceName() != null && la.getEventName() != null)
            activities.add(la);
    }

    //if no activities to render, return
    if (activities.isEmpty())
        return null;

    Map<String, Integer> drActualCount = new HashMap<String, Integer>();
    Map<String, Integer> drCount = new HashMap<String, Integer>();

    //record the actual counts
    for (LoggedActivityDTO laDTO : activities) {
        if (laDTO.getStartDate() != null && laDTO.getEndDate() != null
                && laDTO.getDurationInMillisecs() > minProcessingTimeToRender) {
            if (drActualCount.get(laDTO.getDataResourceName()) == null) {
                drActualCount.put(laDTO.getDataResourceName(), new Integer(4));
                drCount.put(laDTO.getDataResourceName(), new Integer(0));
            } else {
                Integer theCount = drActualCount.get(laDTO.getDataResourceName());
                theCount = new Integer(theCount.intValue() + 4);
                drActualCount.remove(laDTO.getDataResourceName());
                drActualCount.put(laDTO.getDataResourceName(), theCount);
            }
        }
    }

    StringBuffer fileNameBuffer = new StringBuffer(fileNamePrefix);
    if (dataResource != null) {
        fileNameBuffer.append("-resource-");
        fileNameBuffer.append(dataResource.getKey());
    } else if (dataProvider != null) {
        fileNameBuffer.append("-provider-");
        fileNameBuffer.append(dataProvider.getKey());
    }
    fileNameBuffer.append(".png");

    String fileName = fileNameBuffer.toString();
    String filePath = System.getProperty("java.io.tmpdir") + File.separator + fileName;

    File fileToCheck = new File(filePath);
    if (fileToCheck.exists()) {
        return fileName;
    }

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    boolean generateChart = false;

    int count = 1;
    int dataResourceCount = 1;

    Collections.sort(activities, new Comparator<LoggedActivityDTO>() {
        public int compare(LoggedActivityDTO o1, LoggedActivityDTO o2) {
            if (o1 == null || o2 == null || o1.getDataResourceKey() != null || o2.getDataResourceKey() != null)
                return -1;
            return o1.getDataResourceKey().compareTo(o2.getDataResourceKey());
        }
    });

    String currentDataResourceKey = activities.get(0).getDataResourceKey();

    for (LoggedActivityDTO laDTO : activities) {
        if (laDTO.getStartDate() != null && laDTO.getEndDate() != null
                && laDTO.getDurationInMillisecs() > minProcessingTimeToRender) {

            if (currentDataResourceKey != null && !currentDataResourceKey.equals(laDTO.getDataResourceKey())) {
                dataResourceCount++;
                count = count + 1;
                currentDataResourceKey = laDTO.getDataResourceKey();
            }
            TimeSeries s1 = new TimeSeries(laDTO.getDataResourceName(), "Process time period",
                    laDTO.getEventName(), Hour.class);
            s1.add(new Hour(laDTO.getStartDate()), count);
            s1.add(new Hour(laDTO.getEndDate()), count);
            dataset.addSeries(s1);
            generateChart = true;
        }
    }

    if (!generateChart)
        return null;

    // create a pie chart...
    final JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false);

    XYPlot plot = chart.getXYPlot();
    plot.setWeight(10);
    plot.getRangeAxis().setAutoRange(false);
    plot.getRangeAxis().setRange(0, drCount.size() + 1);
    plot.getRangeAxis().setAxisLineVisible(false);
    plot.getRangeAxis().setAxisLinePaint(Color.WHITE);
    plot.setDomainCrosshairValue(1);
    plot.setRangeGridlinesVisible(false);
    plot.getRangeAxis().setVisible(false);
    plot.getRangeAxis().setLabel("datasets");

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setItemLabelsVisible(true);
    MyXYItemLabelGenerator labelGenerator = new MyXYItemLabelGenerator();
    labelGenerator.setDataResourceActualCount(drActualCount);
    labelGenerator.setDataResourceCount(drCount);
    renderer.setItemLabelGenerator(labelGenerator);

    List<TimeSeries> seriesList = dataset.getSeries();
    for (TimeSeries series : seriesList) {
        if (((String) series.getRangeDescription()).startsWith("extraction")) {
            renderer.setSeriesPaint(seriesList.indexOf(series), Color.RED);
        } else {
            renderer.setSeriesPaint(seriesList.indexOf(series), Color.BLUE);
        }
        renderer.setSeriesStroke(seriesList.indexOf(series), new BasicStroke(7f));
    }

    int imageHeight = 30 * dataResourceCount;
    if (imageHeight < 100) {
        imageHeight = 100;
    } else {
        imageHeight = imageHeight + 100;
    }

    final BufferedImage image = new BufferedImage(900, imageHeight, BufferedImage.TYPE_INT_RGB);
    KeypointPNGEncoderAdapter adapter = new KeypointPNGEncoderAdapter();
    adapter.setQuality(1);
    try {
        adapter.encode(image);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    final Graphics2D g2 = image.createGraphics();
    g2.setFont(new Font("Arial", Font.PLAIN, 11));
    final Rectangle2D chartArea = new Rectangle2D.Double(0, 0, 900, imageHeight);

    // draw
    chart.draw(g2, chartArea, null, null);

    //styling
    chart.setPadding(new RectangleInsets(0, 0, 0, 0));
    chart.setBorderVisible(false);
    chart.setBackgroundImageAlpha(0);
    chart.setBackgroundPaint(Color.WHITE);
    chart.setBorderPaint(Color.LIGHT_GRAY);

    try {
        FileOutputStream fOut = new FileOutputStream(filePath);
        ChartUtilities.writeChartAsPNG(fOut, chart, 900, imageHeight);
        return fileName;
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:asl.util.PlotMaker2.java

public void writePlot(String fileName) {
    //System.out.format("== plotTitle=[%s] fileName=[%s]\n", plotTitle, fileName);

    File outputFile = new File(fileName);

    // Check that we will be able to output the file without problems and if not --> return
    if (!checkFileOut(outputFile)) {
        System.out.format("== plotMaker: request to output plot=[%s] but we are unable to create it "
                + " --> skip plot\n", fileName);
        return;/*from   w w w .j av a  2s. c  om*/
    }

    NumberAxis horizontalAxis = new NumberAxis("x-axis default"); // x = domain

    if (fileName.contains("nlnm") || fileName.contains("coher") || fileName.contains("stn")) { // NLNM or StationDeviation 
        horizontalAxis = new LogarithmicAxis("Period (sec)");
        horizontalAxis.setRange(new Range(1, 11000));
        horizontalAxis.setTickUnit(new NumberTickUnit(5.0));
    } else { // EventCompareSynthetics/StrongMotion
        horizontalAxis = new NumberAxis("Time (s)");
        double x[] = panels.get(0).getTraces().get(0).getxData();
        horizontalAxis.setRange(new Range(x[0], x[x.length - 1]));
    }

    CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis);
    combinedPlot.setGap(15.);

    // Loop over (3) panels for this plot:

    for (Panel panel : panels) {

        NumberAxis verticalAxis = new NumberAxis("y-axis default"); // y = range

        if (fileName.contains("nlnm") || fileName.contains("stn")) { // NLNM or StationDeviation 
            verticalAxis = new NumberAxis("PSD 10log10(m**2/s**4)/Hz dB");
            verticalAxis.setRange(new Range(-190, -95));
            verticalAxis.setTickUnit(new NumberTickUnit(5.0));
        } else if (fileName.contains("coher")) { // Coherence
            verticalAxis = new NumberAxis("Coherence, Gamma");
            verticalAxis.setRange(new Range(0, 1.2));
            verticalAxis.setTickUnit(new NumberTickUnit(0.1));
        } else { // EventCompareSynthetics/StrongMotion
            verticalAxis = new NumberAxis("Displacement (m)");
        }

        Font fontPlain = new Font("Verdana", Font.PLAIN, 14);
        Font fontBold = new Font("Verdana", Font.BOLD, 18);
        verticalAxis.setLabelFont(fontBold);
        verticalAxis.setTickLabelFont(fontPlain);
        horizontalAxis.setLabelFont(fontBold);
        horizontalAxis.setTickLabelFont(fontPlain);

        XYSeriesCollection seriesCollection = new XYSeriesCollection();
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, horizontalAxis, verticalAxis, renderer);
        xyplot.setDomainGridlinesVisible(true);
        xyplot.setRangeGridlinesVisible(true);
        xyplot.setRangeGridlinePaint(Color.black);
        xyplot.setDomainGridlinePaint(Color.black);

        // Plot each trace on this panel:
        int iTrace = 0;
        for (Trace trace : panel.getTraces()) {

            XYSeries series = new XYSeries(trace.getName());

            double xdata[] = trace.getxData();
            double ydata[] = trace.getyData();
            for (int k = 0; k < xdata.length; k++) {
                series.add(xdata[k], ydata[k]);
            }

            renderer.setSeriesPaint(iTrace, trace.getColor());
            renderer.setSeriesStroke(iTrace, trace.getStroke());
            renderer.setSeriesLinesVisible(iTrace, true);
            renderer.setSeriesShapesVisible(iTrace, false);

            seriesCollection.addSeries(series);

            iTrace++;
        }

        // Add Annotations for each trace - This is done in a separate loop so that
        //                      the upper/lower limits for this panel will be known
        double xmin = horizontalAxis.getRange().getLowerBound();
        double xmax = horizontalAxis.getRange().getUpperBound();
        double ymin = verticalAxis.getRange().getLowerBound();
        double ymax = verticalAxis.getRange().getUpperBound();
        double delX = Math.abs(xmax - xmin);
        double delY = Math.abs(ymax - ymin);

        // Annotation (x,y) in normalized units - where upper-right corner = (1,1)
        double xAnn = 0.97; // Right center coords of the trace name (e.g., "00-LHZ")
        double yAnn = 0.95;

        double yOff = 0.05; // Vertical distance between different trace legends

        iTrace = 0;
        for (Trace trace : panel.getTraces()) {
            if (!trace.getName().contains("NLNM") && !trace.getName().contains("NHNM")) {
                // x1 > x2 > x3, e.g.:
                //  o-------o   00-LHZ
                //  x3     x2       x1

                double scale = .01; // Controls distance between trace label and line segment
                double xL = .04; // Length of trace line segment in legend

                double xAnn2 = xAnn - scale * trace.getName().length();
                double xAnn3 = xAnn - scale * trace.getName().length() - xL;

                double x1 = xAnn * delX + xmin; // Right hand x-coord of text in range units
                double x2 = xAnn2 * delX + xmin; // x-coord of line segment end in range units
                double x3 = xAnn3 * delX + xmin; // x-coord of line segment end in range units

                double y = (yAnn - (iTrace * yOff)) * delY + ymin;

                if (horizontalAxis instanceof LogarithmicAxis) {
                    double logMin = Math.log10(xmin);
                    double logMax = Math.log10(xmax);
                    delX = logMax - logMin;
                    x1 = Math.pow(10, xAnn * delX + logMin);
                    x2 = Math.pow(10, xAnn2 * delX + logMin);
                    x3 = Math.pow(10, xAnn3 * delX + logMin);
                }
                xyplot.addAnnotation(new XYLineAnnotation(x3, y, x2, y, trace.getStroke(), trace.getColor()));
                XYTextAnnotation xyText = new XYTextAnnotation(trace.getName(), x1, y);
                xyText.setFont(new Font("Verdana", Font.BOLD, 18));
                xyText.setTextAnchor(TextAnchor.CENTER_RIGHT);
                xyplot.addAnnotation(xyText);
            }
            iTrace++;
        }

        combinedPlot.add(xyplot, 1);

    } // panel

    final JFreeChart chart = new JFreeChart(combinedPlot);
    chart.setTitle(new TextTitle(plotTitle, new Font("Verdana", Font.BOLD, 18)));
    chart.removeLegend();

    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, 1400, 1400);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");

    }

}

From source file:com.vgi.mafscaling.VECalc.java

protected void createChart(JPanel plotPanel, String xAxisName, String yAxisName) {
    JFreeChart chart = ChartFactory.createScatterPlot(null, null, null, null, PlotOrientation.VERTICAL, false,
            true, false);//from w ww.  j  a  v  a2s . co  m
    chart.setBorderVisible(true);

    chartPanel = new ChartPanel(chart, true, true, true, true, true);
    chartPanel.setAutoscrolls(true);
    chartPanel.setMouseZoomable(false);

    GridBagConstraints gbl_chartPanel = new GridBagConstraints();
    gbl_chartPanel.anchor = GridBagConstraints.CENTER;
    gbl_chartPanel.insets = new Insets(3, 3, 3, 3);
    gbl_chartPanel.weightx = 1.0;
    gbl_chartPanel.weighty = 1.0;
    gbl_chartPanel.fill = GridBagConstraints.BOTH;
    gbl_chartPanel.gridx = 0;
    gbl_chartPanel.gridy = 1;
    plotPanel.add(chartPanel, gbl_chartPanel);

    XYLineAndShapeRenderer lineRenderer = new XYLineAndShapeRenderer();
    lineRenderer.setUseFillPaint(true);
    lineRenderer.setBaseToolTipGenerator(
            new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                    new DecimalFormat("0.00"), new DecimalFormat("0.00")));

    Stroke stroke = new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, null, 0.0f);
    lineRenderer.setSeriesStroke(0, stroke);
    lineRenderer.setSeriesPaint(0, Color.RED);
    lineRenderer.setSeriesShape(0, ShapeUtilities.createDiamond((float) 2.5));

    lineRenderer.setLegendItemLabelGenerator(new StandardXYSeriesLabelGenerator() {
        private static final long serialVersionUID = 7593430826693873496L;

        public String generateLabel(XYDataset dataset, int series) {
            XYSeries xys = ((XYSeriesCollection) dataset).getSeries(series);
            return xys.getDescription();
        }
    });

    NumberAxis xAxis = new NumberAxis(xAxisName);
    xAxis.setAutoRangeIncludesZero(false);
    NumberAxis yAxis = new NumberAxis(yAxisName);
    yAxis.setAutoRangeIncludesZero(false);

    XYSeriesCollection lineDataset = new XYSeriesCollection();

    XYPlot plot = chart.getXYPlot();
    plot.setRangePannable(true);
    plot.setDomainPannable(true);
    plot.setDomainGridlinePaint(Color.DARK_GRAY);
    plot.setRangeGridlinePaint(Color.DARK_GRAY);
    plot.setBackgroundPaint(new Color(224, 224, 224));

    plot.setDataset(0, lineDataset);
    plot.setRenderer(0, lineRenderer);
    plot.setDomainAxis(0, xAxis);
    plot.setRangeAxis(0, yAxis);
    plot.mapDatasetToDomainAxis(0, 0);
    plot.mapDatasetToRangeAxis(0, 0);

    LegendTitle legend = new LegendTitle(plot.getRenderer());
    legend.setItemFont(new Font("Arial", 0, 10));
    legend.setPosition(RectangleEdge.TOP);
    chart.addLegend(legend);
}